<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>七天DeepSeek重建WSP</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  <link rel="stylesheet" href="cellstyle.css">
  <link rel="stylesheet" href="css/selectLineStyle.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="jsonData.js"></script>

</head>
<body>
  <style>
    /*
    "text-align":0
	   单元格对齐方： 
     0 水平左对齐   1 水平居中  2 水平右对齐   3 垂直顶部对齐  4 垂直居中对齐  5 垂直底部对齐 6 
    */
   
    /* 设置 canvas 的初始显示位置 */
    #myCanvas {
       position: relative;  /* 或者使用 'relative', 'fixed', 或 'sticky' */
       top: 10px;         /* 距离顶部的距离 */
       left: 100px;         /* 距离左边的距离 */
      
       border: 1px solid #ccc; /* 设置 canvas 的边框颜色 */
       z-index: 1;
     }

     #mainCanvas {
    border: 1px solid black;
  }

  .cursorCoordinates{
    font-size: 8px;
  }

  .active {
    background-color: #4CAF50; /* 选中项的背景色，可根据需要调整 */
    color: white; /* 选中项的文字颜色，可根据需要调整 */
}


.navbar {
    background: #333;
    overflow: auto;
    white-space: nowrap;
    position: relative;

    background-image: url('imgs/menu_gb.png'); /* 设置背景图片 */
    background-position: right center; /* 背景图片对齐到右边，垂直方向居中 */
    background-repeat: no-repeat; /* 背景图片不重复 */
}

.menu {
    display: inline-block;
    color: white;
    padding: 14px 20px;
    cursor: pointer;
}

/* 分割线样式调整 */
.menu.right-border {
    position: relative; /* 为了使用绝对定位的伪元素 */
}

.menu.right-border::after {
    content: ""; /* 伪元素内容为空 */
    position: absolute; /* 使用绝对定位 */
    right: 0; /* 定位到容器的右侧 */
    height: 80%; /* 分割线的高度为容器高度的80% */
    width: 1px; /* 分割线的宽度 */
    background-color: #767373; /* 分割线颜色 */
    top: 10%; /* 顶部偏移，使其垂直居中 */
}

.menu.left-border {
    position: relative; /* 为了使用绝对定位的伪元素 */
}
.menu.left-border::before {
    content: "";
    position: absolute;
    left: 0;
    top: 10%;
    height: 80%;
    width: 1px;
    background-color: #767373;
}

.menu:hover {
    background-color: #555;
}

.submenu-container {
    display: none;
    background:transparent;
    padding: 1px;
    border: 1px solid #5b5858;
}

.submenu {
    display: none;
    padding: 1px;
  
}
.submenu2 {
    display: none;
    padding: 1px;
  
}
.submenu div {
    margin: 1px;
    display: inline-block;
    background:transparent;
    padding: 3px 1px;
    border-radius: 0px;
    
}
.submenu2 div {
    margin: 1px;
    display: flex;
    background:transparent;
    padding: 3px 1px;
    border-radius: 0px;
    
}

.setOneRow{
 
  margin: 1px;
  display: inline-block;
   background:transparent;
   padding: 3px 1px;
   border-radius: 0px;
}


.button-container {
    position: relative;
    display: inline-block;
}

.button-container2 {
    position: relative;
    display: inline-block;
}

.button {
    padding: 10px;
    border: 0px solid transparent;
    background-color: transparent;
    cursor: pointer;
    font-size: 16px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    transition: border 0.3s;
}



.button:hover {
    border-color: #f2f2f2;
    border: 0px solid transparent;
}

.button img {
    width: 32px;
    height: 32px;
}

.button span {
    margin-top: 5px;
}

.icon-button {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 10px;
    margin-left: 1px;
    cursor: pointer;
    background-color: transparent;
    color: white;
    border: none;
    border-radius: 4px;
}

.icon-button img {
    width: 18px;
    height: 18px;
    margin-bottom: 1px;
}

.icon-button:hover {
    background-color: rgba(255, 255, 255, 0.2);
}

.icon-button span {
    font-size: 2px; /* 设置文字字体大小为8px */
}


.menu-group {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 0px;
  }

  .menu-group .buttons {
    display: flex;
  }
  
  .buttons2 {
            display: flex; /* 使按钮水平排列 */
            align-items: center;
            width: 32px;
            height: 32px;
        }

  .menu-item:last-child {
    margin-right: 0;
  }

  .menu-item:hover {
    background-color: #d1d1d1;
  }



  .divider {
    flex: none;
    align-self: stretch; /* 使分割线高度自适应navbar的高度 */
    width: 2px;
    height: 80px;
    border-left: 1px solid #c2c0c0; /* 使用边框作为分割线 */
    margin: 0 1px; /* 两侧的间距 */
  }

  .menu-group {
    display: flex;
    flex-direction: column;
    align-items: center; /* 水平居中子元素 */
    justify-content: center; /* 垂直居中子元素，如果需要的话 */
    padding: 0 20px;
}

.group-title {
    text-align: center;
    font-size: 14px;
    margin-top: 5px;
    width: 100%; /* 确保标题宽度与父容器相同，以便text-align生效 */
}

.menu-item {
    display: flex;
    flex-direction: column; /* 使内容垂直排列 */
    align-items: center; /* 水平居中对齐子元素 */
    justify-content: center; /* 垂直居中对齐子元素，如果有必要的话 */
    padding: 5px 10px; /* 或根据实际情况调整内边距 */
    cursor: pointer;
    background-color: transparent;
    border: none;
    margin-right: 5px; /* 保持原有右边距 */
    transition: background-color 0.3s; /* 保持背景颜色的渐变效果 */
}


.menu-item2 {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 5px 10px;
            cursor: pointer;
            background-color: transparent;
            border: none;
            margin-right: 5px; /* 为按钮之间提供间距 */
        }
.icon {
    width: 32px; /* 或根据实际图标大小进行调整 */
    height: 32px; /* 或根据实际图标大小进行调整 */
    margin-bottom: 5px; /* 在图标和文字之间添加一些间隙 */
}



  .canvas-popup {
    display: none;
    position: absolute; /* 绝对定位 */
    z-index: 10; /* 确保画布位于按钮之上 */
    background: #fff;
    box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.2); /* 外部阴影 */
  }

  /* 调整画布尺寸以匹配网格 */
  #canvasPopup {
    width: 300px; /* 宽度为5个单元格+50像素的偏移 */
    height:520px; /* 高度为5个单元格+50像素的偏移 */
  }


  #text-input {
    position: absolute; /* 绝对定位，以便可以准确放置在Canvas上 */
    z-index: 1000; /* 确保它位于Canvas上方 */
    border: none; /* 去除边框 */
    outline: none; /* 去除焦点轮廓 */
    background: transparent; /* 背景透明 */
    color: black; /* 文本颜色，根据需要调整 */
    width: auto; /* 宽度自适应，或根据需要调整 */
    height: auto; /* 高度自适应，或根据需要调整 */
    padding: 2; /* 去除内边距 */
    margin: 2; /* 去除外边距 */
    
  }

  .divider_parent {
    flex: none;
    align-self: stretch; /* 使分割线高度自适应navbar的高度 */
    width: 2px;
    border-left: 1px solid #c2c0c0; /* 使用边框作为分割线 */
    margin: 0 10px; /* 两侧的间距 */
  }
 
  .areaBox {
    display: flex;
    width: 430px;
    padding: 3 1;
    flex-direction: column; /* 设置Flex容器的主轴方向为垂直 */
}

.areaBox > div {
    margin-bottom: 1px; /* 为子元素之间添加一些间隔 */
}

/* 最后一个子元素不需要底部间隔 */
.areaBox > div:last-child {
    margin-bottom: 0;
}

.div1, .div2 {
    display: flex;
    width: 430px;
    flex-direction: row; /* 设置子元素的排列方向为水平 */
}

.div1 > *, .div2 > * {
    margin-right: 10px; /* 为子元素之间添加一些间隔 */
}

/* 最后一个子元素不需要右侧间隔 */
.div1 > *:last-child, .div2 > *:last-child {
    margin-right: 0;
}

.fontAreaTitle{
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: small;
    width: 280px;
}

.floorOfTools {
    display: flex; /* 启用Flexbox布局 */
    flex-direction: column; /* 确保子元素按垂直方向排列 */
    gap: 20px; /* 根据需要调整子元素之间的间隔 */
    border-color: #4CAF50;
    border-width: 2px;
}

.fontToolsBox {
    display: flex; /* 启用Flexbox布局，确保子元素水平排列 */
    flex-direction: row; 
    gap: 10px; /* 根据需要调整子元素之间的间隔 */
}

.fontToolsBox > div {
    padding: 10px; /* 根据需要调整内边距 */
    background-color: #f0f0f0; /* 轻灰色背景 */
    border-radius: 5px; /* 轻微的圆角 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加盒阴影以实现高光效果 */
    transition: background-color 0.3s ease, box-shadow 0.3s ease; /* 平滑过渡效果 */
}

.fontToolsBox > div:hover {
    background-color: #e9e9e9; /* 鼠标悬停时的背景色变化 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); /* 鼠标悬停时增加阴影以强化高光效果 */
}


  .selectors {
            display: flex;
            align-items:center; /* 垂直居中 */
            justify-content: start; /* 水平方向从头开始排列 */
            gap: 10px; /* 下拉框之间的间距 */
        }

        select {
            flex-grow: 1; /* 使下拉框能够填充额外的空间 */
        }
        #group-row-column2 {
    display: flex;
    flex-direction: column;
}

.selectors, .selectors2 {
    display: flex;
    align-items: center;
    gap: 10px; /* 根据需要调整间隙大小 */
}

.icon {
    width: 16px; /* 根据实际情况调整图标大小 */
    height: 16px;
    align-items: center;
    vertical-align: middle;
}

.group-title {
    margin-top: 20px; /* 根据需要调整间隙大小 */
    font-size: small;
}
.divider2 {
            width: 2px; /* 分隔线的宽度 */
            background-color: #ccc; /* 分隔线的颜色 */
            margin: 0 20px; /* 分隔线的外边距 */
            height: auto; /* 根据内容调整高度 */
            align-self: stretch; /* 使分隔线填满容器的高度 */
        }

.child {
        width: 100px; /* 设置子DIV的宽度，根据需要调整 */
        height: 100px; /* 设置子DIV的高度，根据需要调整 */
        background-color: lightblue; /* 设置子DIV的背景颜色，仅为示例 */
        text-align: center; /* 文本居中 */
        line-height: 100px; /* 让文本垂直居中显示 */
    }

.tools_container {
    display: flex; /* 启用Flexbox布局 */
    flex-direction: column; /* 子元素沿垂直方向排列 */
    align-items: center; /* 子元素在交叉轴上居中对齐 */
}

#Main_File_fileButton {
    padding: 10px 20px;
    cursor: pointer;
}

    #Main_File_fileButton {
    padding: 10px 20px;
    cursor: pointer;
}

.Main_File_menu {
    list-style-type: none;
    padding: 0;
    margin: 0;
    position: absolute;
    background-color: #f2f2f2;
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    display: none;
    width: 120px; /* 设置菜单宽度 */
    z-index: 1000;
}

.Main_File_menu > li {
    position: relative;
    padding: 10px 10px 10px 34px;
    cursor: pointer;
    background-repeat: no-repeat;
    background-position: 10px center;
}

.Main_File_submenu {
    display: none;
    position: absolute;
    left: 100%;
    top: 0;
    width: 140px;
    background-color: #ffffff;
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.Main_File_submenu li {
    padding: 10px 10px 10px 34px;
    background-color: #f2f2f2;
    background-repeat: no-repeat;
    background-position: 10px center;
}

.Main_File_menu > li:hover {
    background-color: #ddd;
}

.Main_File_submenu li:hover {
    background-color: #ddd;
}

/* 图标样式也需要添加前缀 */
.Main_File_icon-new {
    background-image: url('imgs/new.png');
}

.Main_File_icon-open {
    background-image: url('imgs/open.png');
}

.Main_File_icon-save {
    background-image: url('imgs/save.png');
}

.Main_File_icon-save-as {
    background-image: url('imgs/save_as.png');
}

.Main_File_icon-close {
    background-image: url('imgs/close.png');
}

.Main_File_icon-pdf {
    background-image: url('imgs/pdf.png');
}

.Main_File_icon-doc {
    background-image: url('imgs/doc.png');
}

.Main_File_icon-img {
    background-image: url('imgs/image.png');
}
/*分表管理样式*/
#mag_tab_dialog { 
  display: none; 
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

#mag_tab_dialog .list-box-container {
  display: flex;
  justify-content: space-between;
}

.mag_tab_list-box { 
  margin-top: 20px; 
  flex: 1;
  margin-left: 10px;
  margin-right: 10px;
}

table { 
  width: 100%; 
  border-collapse: collapse; 
}

th, td { 
  border: 1px solid #ddd; 
  padding: 8px; 
  text-align: left; 
}

.mag_tab_highlighted {
    background-color: #f0f0f0;
}

/*分表管理样式*/


    </style>

    
&nbsp;&nbsp;
<div id="cell-dialog" title="单元格属性设置" style="display:none;">
  <div class="dialog-instructions">
      请点击单元格边，设定单元格边线是否显示
  </div>
  <div class="cell" id="cell">
      <div class="edge" id="cell-edge"></div>
  </div>
  <div class="dialog-actions">
      <button id="cancel-button">取消</button>
      <button id="confirm-button">确定</button>
  </div>
</div>


<input type="text" id="text-input" />
<div class="navbar">
      <div class="menu right-border" data-target="Files" id="Main_File_fileButton">文件...</div>
      <div class="menu right-border" data-target="about">关于蛇年七天用AI</div>
      <div class="icon-button" id="undo">
        <img src="imgs/cancel_w.png" alt="撤销" id="undo">
        
      </div>
      <div class="icon-button" id="redo">
        <img src="imgs/redo_w.png" alt="重做">
        
      </div>

      <div class="icon-button" id="redo">
        <img src="imgs/savetocloud.png" alt="保存">
        
      </div>


      
      <div class="menu left-border" data-target="start">开始</div>
      <div class="menu" data-target="insert">表格</div>
      <div class="menu" data-target="mTable">分表管理</div>
      <div class="menu" data-target="reference">引用</div>
      <div class="menu" data-target="view">视图</div>
      <div class="menu" data-target="tools">工具</div>
</div>



<ul id="Main_File_fileMenu" class="Main_File_menu">
    <li class="Main_File_icon-new">新建
        <ul class="Main_File_submenu">
            <li class="Main_File_icon-doc">文档</li>
            <li class="Main_File_icon-img">图片</li>
        </ul>
    </li>
    <li class="Main_File_icon-open">打开</li>
    <li class="Main_File_icon-save">保存</li>
    <li class="Main_File_icon-save-as">另存为
        <ul class="Main_File_submenu">
            <li class="Main_File_icon-pdf">PDF</li>
            <li class="Main_File_icon-img">图片</li>
        </ul>
    </li>
    <li class="Main_File_icon-close">关闭</li>
</ul>



<div class="submenu-container">
  <div class="submenu" id="about">蛇年七天AI: 今天是大年初四，挑战七天重建WPS第4天，用deepseek编写代码对表格及单元格的操作</div>
  <div class="submenu2" id="start">
 
    <div class="button-container">
       <div class="areaBox">
        <div class="div1">
                           
                
                          <select id="fontSelector" ></select>                         
                          <select id="fontSizeSelector"></select>

                          <button class="menu-item" id="incFontSize" data-action="incFontSize">
                              <img src="imgs/font-add.png" alt="字体加大" class="icon">
                          </button>

                          <button class="menu-item" id="minFontSize" data-action="minFontSize">
                              <img src="imgs/font-minus.png" alt="字体减小" class="icon">
                          </button>

                          <button class="menu-item" id="eraser_font">
                              <img src="imgs/eraser.png" alt="清除格式" class="icon">
                          </button>
        </div>     
          
              <div class="div2" id="font_style">    
                  <button class="menu-item" id="Bold"  data-action="setBold">           
                      <img src="imgs/Bold.png" alt="字体加粗" class="icon">
                  </button>

                  <button class="menu-item" id="italic"  data-action="italicOn" >
                      <img src="imgs/italic.png" alt="斜体" class="icon">
                    </button>

                    <button class="menu-item" id="underline"  data-action="underLine">  
                      <img src="imgs/underline.png" alt="下刬线" class="icon">
                    </button>

                    <button class="menu-item" id="deleteline"  data-action="deleteline">  
                      <img src="imgs/deleteLineOnMid.png" alt="删除线" class="icon">
                    </button>

                    <button class="menu-item" id="sign-up">  
                      <img src="imgs/sign-up.png" alt="上标" class="icon">
                    </button>

                    <button class="menu-item" id="selectLineStyle_openDialog"   data-action="selectLineStyle_openDialog">  
                      <img src="imgs/artstyle.png" alt="字体样式" class="icon">
                    </button>

                    <button class="menu-item" id="selectLineColor_openDialog">  
                      <img src="imgs/highlight.png" alt="下线线颜色" class="icon" >
                    </button>

                    <button class="menu-item" id="set_fontcolor">  
                      <img src="imgs/fontcolor.png" alt="字体颜色" class="icon">
                    </button>

                    <button class="menu-item" id="fontshading"  data-action="backgroundColor">  
                      <img src="imgs/fontshading.png" alt="字体底纹" class="icon">   
                    </button>

              </div>
       
          <div class="fontAreaTitle">字体</div>
      
     </div> 




      <div class="divider"></div>
    
      <div class="areaBox">
        <div class="div1">
              <button class="menu-item" id="addindent" data-action="addindent">
                  <img src="imgs/addindent.png" alt="增加缩进" class="icon">
              </button>
              <button class="menu-item" id="minusindent" data-action="minusindent">
                  <img src="imgs/minusindent.png" alt="减少缩进" class="icon">
              </button>
              <button class="menu-item" id="valign_top" data-action="valign_top">
                <img src="imgs/valign_top.png" alt="垂直居顶" class="icon">
              </button>

              <button class="menu-item" id="valign_midd" data-action="valign_midd">
                <img src="imgs/valign_midd.png" alt="项目符号" class="icon">
              </button>

              <button class="menu-item" id="valign_bottom" data-action="valign_bottom">
                <img src="imgs/valign_bottom.png" alt="编辑符号显示" class="icon">
              </button>

              <button class="menu-item" id="tab_flag" data-action="tab_flag">
                <img src="imgs/tab.png" alt="制表位" class="icon">
              </button>
          </div>

          <div class="div2">
              <button class="menu-item" id="left_align" data-action="left_align">
                  <img src="imgs/left_align.png" alt="左对齐" class="icon">
              </button>
              <button class="menu-item" id="midd_align"  data-action="midd_align">
                  <img src="imgs/midd_align.png" alt="居中" class="icon">
              </button>
              <button class="menu-item" id="right_align"  data-action="right_align">
                <img src="imgs/right_align.png" alt="右对齐" class="icon">
              </button>

              <button class="menu-item" id="justify_align"  data-action="justify_align">
                <img src="imgs/justify.png" alt="两端对齐" class="icon">
              </button>

              <button class="menu-item" id="lineheight"   data-action="lineheight">
                <img src="imgs/lineheight.png" alt="行距" class="icon">
              </button>

              <button class="menu-item" id="v_center"   data-action="v_center">
                <img src="imgs/v_center.png" alt="单元格边样式" class="icon">
              </button>
        </div>


      
          <div class="fontAreaTitle">段落</div>
      </div>
      </div>
  
    </div>
    



  <div class="submenu" id="insert">
 
      <div class="button-container">
    
      
              <div class="menu-group" id="group-row-column">
                  <div class="buttons">
                      <button class="menu-item" id="show_insert_table">
                          <img src="imgs/insert_table.png" alt="绘制表格" class="icon">绘制表格
                      </button>
                      <button class="menu-item" id="addRow">
                          <img src="imgs/insertr.png" alt="插入行" class="icon">插入行
                      </button>
                      <button class="menu-item" id="addCol">
                          <img src="imgs/insertc.png" alt="插入列" class="icon">插入列
                      </button>
                      <button class="menu-item" id="deleteLastRow">
                          <img src="imgs/deleteRow.png" alt="删除行" class="icon">删除行
                      </button>
                      <button class="menu-item" id="deleteLastColumn">
                          <img src="imgs/deleteCol.png" alt="删除列" class="icon">删除列
                      </button>
                  </div>
          			<div class="group-title">行和列</div>
      </div>
      
      <div class="divider"></div>
      
      <div class="menu-group" id="group-merge-split">
          <div class="buttons">
              <button class="menu-item" id="MergeCells">
                  <img src="imgs/merge.png" alt="合并单元格" class="icon">合并单元格
              </button>
              <button class="menu-item" id="splitCells">
                  <img src="imgs/split.png" alt="拆分单元格" class="icon">拆分单元格
              </button>
              <button class="menu-item" id="setCell">
                <img src="imgs/cell_style.png" alt="设置单元格" class="icon">单元格边样式
            </button>

            <button class="menu-item" id="hasCheckCtrl">
              <img src="imgs/has_check_ctrl.png" alt="设置单元格" class="icon">单元格选控件
          </button>
            
          </div>
          <div class="group-title">合并拆分</div>
      
      
      
        </div>
       
  </div>
 
</div>

<div class="submenu" id="mTable">
 
  <div class="button-container">

  
          <div class="menu-group" id="group-row-column">
              <div class="buttons">
                  <button class="menu-item" id="show_subTab_manager">
                      <img src="imgs/sub_table.png" alt="分表列表" class="icon">分表管理
                  </button>
                  <button class="menu-item" id="subTab_ctrl">
                      <img src="imgs/table_ctrl.png" alt="分表控件" class="icon">分表控件
                  </button>
                  <button class="menu-item" id="select_line_for_Tab">
                      <img src="imgs/slect_row.png" alt="运行表单" class="icon">运行表单
                  </button>
             
              </div>
            <div class="group-title">分表管理</div>
  </div>
  
  <div class="divider"></div>
  
  <div class="menu-group" id="group-merge-split">
      <div class="buttons">
          <button class="menu-item" id="tab_program">
              <img src="imgs/index_title.png" alt="编程" class="icon">表索引管理
          </button>
          <button class="menu-item" id="var_manage">
              <img src="imgs/var_flag.png" alt="变量" class="icon">表变量管理
          </button>
        
      </div>
      <div class="group-title">表格编程</div>
  
  
  
    </div>
   
</div>

</div>

</div>


<div id="cursorCoordinates"></div>

<canvas id="canvasPopup" class="canvas-popup" width="300" height="520"></canvas>
<canvas id="myCanvas" width="1300" height="1200"></canvas>
<canvas id="menuCanvas" width="150" height="100" style="display: none; position: absolute; z-index: 5;"></canvas>

<button id="mag_tab_open-dialog">制表</button>

    <div id="mag_tab_dialog" title="分表管理">
        <button id="mag_tab_add-table">增加子表</button>
        <div class="list-box-container">
          <div class="mag_tab_list-box" id="mag_tab_table1">
            <table>
              <thead>
                <tr><th>序号</th><th>分表名称</th><th>删除</th><th>修改</th> <th>增加行</th></tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
          <div class="mag_tab_list-box" id="mag_tab_table2">
            <table>
              <thead>
                <tr><th>序号</th><th>行号</th><th>删除</th></tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </div>
    
    <div id="mag_tab_add-subtable-dialog" title="增加子表" style="display: none;">
        <form id="mag_tab_add-subtable-form">
          <label for="mag_tab_subtableName">名称：</label>
          <input type="text" id="mag_tab_subtableName" name="subtableName"><br><br>
          <input type="button" id="mag_tab_confirm-add-subtable" value="确认">
        </form>
      </div>

<div id="selectLineStyle_dialog" class="selectLineStyle_dialog">
  <br>
  <button id="selectLineStyle_straightLine"></button>
  <button id="selectLineStyle_doubleLine"></button>
  <button id="selectLineStyle_wavyLine"></button>
  <button id="selectLineStyle_noLine"></button>  
</div>


<div id="selectLineColor_dialog" class="selectLineColor_dialog">
  <button id="selectLineColor_black"></button>
  <button id="selectLineColor_red"></button>
  <button id="selectLineColor_green"></button>
  <button id="selectLineColor_noColor"></button>
</div>

<!-- 隐藏的颜色选择器 -->
<input type="color" id="hidden-color-picker" style="display: none;">
<script>

  // 画布上页面的位置和大小
  const pageX = 20; // 画布左边界偏移20像素
  const pageY = 20; // 画布上边界偏移20像素
  const pageWidth = 794; // 页面宽度
  const pageHeight = 1123; // 页面高度
  var   lastTableTotalWidth=0;  //最新的表格宽度更新
  var   selectStartX=0;  //选中表格的起始X坐标
  var   selectStartY=0;  //选中表格的起始Y坐标
  var   isSelecting = false;
  var   selectionStart = {};
  var   selectedCells = [];
  var   currentSelection = [];//记录当前选择单元各的 数组下标集
  var   jsonData = [];
  var   tableTotalWidth=0;
  var   tableTotalHeight=0;
  var   tableOffsetX=60;  //表格与画布的左边距
  var   tableOffsetY=110; //表格与画布的顶边距
  var   whereCurIs=0;     //在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部
  var   cursorIsInSideOfCell=0;//光标在单元格内部，，offset之内
  var   g_selectedColumn=-1;  //全局选中的列
  var   g_selectedRow=-1;     //全局选中的行
  var   g_selectedCellWidth_L=0;  //全局选单元格宽度
  
  var   g_selectedCellWidth_R=0;
  var   g_selectedCellHeight=0;  //全局选单元格高度
  var   temp_left_cell_width;
  var   temp_right_cell_width;
  var   isIntoMenuSelection=0;//弹起菜单，，其它绘图操作禁用

  let   isSelectingForCell = false;                                     //是否正在选择单元格
  let   selectionStartX, selectionStartY, selectionEndX, selectionEndY; //选择区域的起始和结束坐标

  var canvas1 = $('#canvasPopup')[0];

  const menuCanvas = document.getElementById('menuCanvas');
  const menuCtx = menuCanvas.getContext('2d');

    var ctx1 = canvas1.getContext('2d');
    var gridSize = 15;
    var gridSpacing = 5;
    var rowSpacing = 5;
    var rows = 24, columns = 14;
    var gridColor = '#000';
    var highlightColor = 'rgba(173, 216, 230, 0.5)'; // Light blue color

    // 确保 history 和 redoStack 是数组
    var historyStack = [];
    var redoStack = [];
    var checkedBoxImage = new Image();
    var checkBoxImage = new Image();

    var originalY = 0;
    var maxWidth = 360;
    var lineHeight = 25;
    var align = 0;
    var displayMode = 1;
    var g_verticalAlign = 0;
    var font = 'Arial';
    var fontSize = 16;
    var indent = 0; // 首行缩进的字符数量
    // 全局变量来跟踪斜体状态
    var italic = 0; // 0表示正常，1表示斜体
    var underlineColor='rgb(255, 255, 0)';
    var underline=0;
    var underlineStyle = 'straight';
    var backgroundColor='transparent'
    var currentLineSpacing = 0; // 初始行距
    var bold = 0; // 初始时不加粗
    var strikethrough = 0; // 0表示没有删除线，1表示有删除线



  //绘制下划线：style 0 为直线，1为波浪线，2为双行线
  function drawUnderline(ctx, x, y, width, color, style) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    if (style === 'straight') {
        ctx.moveTo(x, y);
        ctx.lineTo(x + width, y);
    } else if (style === 'wavy') {
        let amplitude = 2;
        let frequency = 5;
        let x1 = x;
        let y1 = y;
        ctx.moveTo(x1, y1);
        for (let i = 0; i < width; i += frequency) {
            ctx.lineTo(x1 + i, y1 + ((i % (frequency * 2)) === 0 ? amplitude : -amplitude));
        }
    } else if (style === 'double') {
        ctx.moveTo(x, y - 2);
        ctx.lineTo(x + width, y - 2);
        ctx.moveTo(x, y + 2);
        ctx.lineTo(x + width, y + 2);
    }
    ctx.stroke();
    }

 
function drawTextInRect(ctx, text, cell_x, cell_y, maxWidth,maxHeight , align, displayMode, verticalAlign, font, fontSize, indent, color, underline, strikethrough, italic, underlineColor, underlineStyle, backgroundColor, lineSpacing,bold) {
 

 var fontStyle = (italic == 1 ? "italic " : "") + (bold == 1 ? "bold " : "");
 ctx.font = fontStyle + fontSize + 'px ' + font;
 ctx.fillStyle = color; // 设置文本颜色


  //////////////////////////////////////////////////////////////////////////////////////
    // 估计文本的高度
    // 注意: 这是一个简单的估计方法，可能不适用于所有字体和情况
     // 使用measureText()测量文本的宽度
     var metrics = ctx.measureText(text);
    var width = metrics.width;
    var height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;

    // 输出文本的宽度和估计的高度
    console.log("A1: Text width: " + width + "px"  );
    console.log("A1: Estimated text height: " + height);

    // 可选: 在Canvas上标出文本区域
    //ctx.strokeRect(drawX, y - metrics.actualBoundingBoxAscent, width, height);
    ///////////////////////////////////////////////////////////////////////////////////////

 var lineHeight=height;
 var indentSize = ctx.measureText(' ').width * indent; // 计算缩进的像素大小
 var lines = displayMode == 1 ? [] : [''];
 var currentLine = '';

 var isFirstLine = true;
 var y=0;
 var x=0;

 if (displayMode == 1) {
     for (let i = 0; i < text.length; i++) {
         var char = text[i];
         var testLine = currentLine + char;
         var metrics = ctx.measureText(testLine);
         var currentLineWidth = maxWidth - (isFirstLine ? indentSize : 0); // 首行减去缩进大小
         if (metrics.width > currentLineWidth && i > 0) {
             lines.push(currentLine);
             currentLine = char;
             isFirstLine = false;
         } else {
             currentLine = testLine;
         }
     }
     lines.push(currentLine);
 } else {
     // 单行模式下，考虑首行缩进
     var singleLineText = text.slice(0, maxWidth / ctx.measureText(' ').width - 3 - indent) + '...';
     lines = [singleLineText];
 }

 var totalHeight = lines.length * lineHeight;
 if (verticalAlign == 1) {
     y = (maxHeight - totalHeight) / 2;   //垂直居中
 } else if (verticalAlign == 2) {
     y = maxHeight - totalHeight;
 } // 顶部对齐不需要调整y
 else{
    y=lineHeight/2;
 }


 y=cell_y+y+2;
//  var canvasOffset = $('#myCanvas').offset(); 
//  var cellStartX = canvasOffset.left+tableOffsetX;
// var cellStartY = canvasOffset.top+tableOffsetY;


 lines.forEach(function(line, index) {

  console.log("A1 参数 Y:"+(y-tableOffsetY)+ "  verticalAlign:"+verticalAlign +" totalHeight:"+totalHeight+" maxHeight:"+maxHeight+ "  lines.length:"+lines.length+ " lineHeight:"+lineHeight+" tableOffset:"+tableOffsetY+" real y:"+y+" line:"+line+" textAlign:"+align+ " underline:"+underline+" fontSize:"+fontSize);
 var words = line.split(' ');
 var lineY = y + index * (lineHeight + lineSpacing);
 // 设置背景颜色
 if (backgroundColor != 'transparent') {
 ctx.fillStyle = backgroundColor;
 var textWidth = ctx.measureText(text).width;
 var backgroundHeight = lineHeight+5;
 var backgroundWidth = textWidth;
 var backgroundX = x+cell_x;
 var backgroundY = y - fontSize+5; // 调整背景位置以适配文本
 ctx.fillRect(backgroundX, backgroundY, backgroundWidth, backgroundHeight+lineSpacing);
 ctx.fillStyle = color; // 重置为文本颜色
 }


 if (align == 3 && words.length > 1) { // 分散对齐
     var totalWidth = words.reduce(function(sum, word) {
         return sum + ctx.measureText(word).width;
     }, 0);
     var remainingSpace = maxWidth - totalWidth;
     var spaceWidth = remainingSpace / (words.length - 1);
     var currentPosition = x;
     
     words.forEach(function(word, wordIndex) {
         ctx.fillText(word, currentPosition, y);
         currentPosition += ctx.measureText(word).width + spaceWidth;
     });
 } 
 else {

     var lineWidth = ctx.measureText(line).width;
     var drawX = x + (index == 0 ? indentSize : 0);
     if (align == 1 ) {
         drawX += (maxWidth - lineWidth) / 2;
     } else if (align == 2 ) {
         drawX += maxWidth - lineWidth;
     }
     drawX=drawX+cell_x;
     ctx.fillText(line, drawX, y);
     console.log("A1 参数 Y:"+(y-tableOffsetY)+ "  verticalAlign:"+verticalAlign +" totalHeight:"+totalHeight+" maxHeight:"+maxHeight+ "  lines.length:"+lines.length+ " lineHeight:"+lineHeight+" drawX:"+drawX);

   

 }

 //下划线绘制逻辑
 if (underline == 1) {
     var underlineY = y + lineHeight/2; // 稍微在文字下方一点
     var textWidth = ctx.measureText(line).width;
     drawUnderline(ctx, drawX, underlineY, textWidth, underlineColor, underlineStyle);
 }

    // 删除线的绘制逻辑
 if (strikethrough == 1) {     
     var strikethroughY = y -lineHeight/4+2 ; // 计算删除线位置，这里的计算方法仅为示例，可能需要调整
     var textWidth = ctx.measureText(line).width;
     drawUnderline(ctx, x+cell_x, strikethroughY, textWidth, underlineColor, underlineStyle);
 }

 y += lineHeight+lineSpacing;

});      

}

	
function drawRoundedRect(ctx, x, y, width, height, radius, fillStyle) {
  ctx.fillStyle = fillStyle;
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.arcTo(x + width, y, x + width, y + height, radius);
  ctx.arcTo(x + width, y + height, x, y + height, radius);
  ctx.arcTo(x, y + height, x, y, radius);
  ctx.arcTo(x, y, x + width, y, radius);
  ctx.closePath();
  ctx.fill();
}

function highlightButton(buttonId, state) {
  const button = document.getElementById(buttonId);
  if (button) { // 确保找到了按钮
    if (state === 1) {
      // 添加高亮样式
      button.classList.add('button-highlight');
    } else if (state === 0) {
      // 移除高亮样式，恢复默认状态
      button.classList.remove('button-highlight');
    }
  }
}


highlightButton('splitCells', 1);

// Menu Drawing function
function drawMenu(x, y) {
  isIntoMenuSelection=1;
  // Set the position of the menu
  $(menuCanvas).css({top: y, left: x}).show();

  // Draw the rounded rectangle
  menuCtx.fillStyle = 'rgba(255, 255, 255, 0.9)';
  menuCtx.shadowColor = 'rgba(0, 0, 0, 0.5)';
  menuCtx.shadowBlur = 1;
  menuCtx.fillRect(5, 5, 140, 90);

  // Draw the title bar
  menuCtx.fillStyle = '#003366';
  menuCtx.fillRect(5, 5, 140, 20);

  // Draw the title text
  menuCtx.fillStyle = 'white';
  menuCtx.font = 'bold 14px Arial';
  menuCtx.fillText('提示', 10, 20);

  // Draw the menu items
  menuCtx.fillStyle = '#003366';
  menuCtx.font = '12px Arial';
  menuCtx.fillText('合并单元格', 10, 50);
  menuCtx.fillText('取消', 10, 80);
}

// Menu item interaction
$(menuCanvas).on('mousemove', function(e) {
  const rect = menuCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Redraw the menu (which clears previous highlights)
  drawMenu(parseInt($(menuCanvas).css('left')), parseInt($(menuCanvas).css('top')));

  // Define menu item bounds
  const mergeCellsItemBounds = { top: 30, bottom: 50 };
  const cancelItemBounds = { top: 60, bottom: 80 };

  // Highlight and re-draw text for 'Merge Cells' item
  if (y > mergeCellsItemBounds.top && y < mergeCellsItemBounds.bottom) {
    // Highlight background
    menuCtx.fillStyle = 'lightblue';
    menuCtx.fillRect(5, 35, 140, 20);
    // Re-draw text
    menuCtx.fillStyle = '#003366';
    menuCtx.fillText('合并单元格', 10, 50);
  }

  // Highlight and re-draw text for 'Cancel' item
  if (y > cancelItemBounds.top && y < cancelItemBounds.bottom) {
    // Highlight background
    menuCtx.fillStyle = 'lightblue';
    menuCtx.fillRect(5, 65, 140, 20);
    // Re-draw text
    menuCtx.fillStyle = '#003366';
    menuCtx.fillText('取消', 10, 80);
  }
});
// Event listener for table right-clicks
$(myCanvas).on('contextmenu', function(e) {
  e.preventDefault(); // Prevent the default context menu from showing

  const rect = myCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Check if we clicked inside a cell
 //这里绘制右键菜单 
    drawMenu(x, y);
  
});



function hideMenu() {
  isIntoMenuSelection=0;//进入菜单选择状态
  menuCanvas.style.display = 'none';
}



  function drawTableFromJson(jsonData) {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var currentX = 0;
  var currentY = 0;

  


  jsonData.forEach(function(rowData, rowIndex) {
    currentX = 0;
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {
        ctx.strokeRect(currentX, currentY, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(cell.content, currentX + cell.width / 2, currentY + cell.height / 2);
      currentX += cell.width;
    });
    currentY += rowData.cells[0].height;
  });
}

 // Function to draw the icon on the canvas
 function drawIcon(x, y) {
    if (iconLoaded && iconVisible) {
      // Clear the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      // Draw the icon
      ctx.drawImage(icon, x - icon.width / 2, y - icon.height / 2);
    }
  }

  // Function to draw the grid
  function drawGrid() {
    ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
    ctx1.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < columns; col++) {
        ctx1.rect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }
    ctx1.strokeStyle = gridColor;
    ctx1.stroke();
  }



  // Function to highlight squares
  function highlightSquares(x, y) {
    var colEnd = Math.floor(x / (gridSize + gridSpacing));
    var rowEnd = Math.floor(y / (gridSize + rowSpacing));

    colEnd = colEnd >= columns ? columns - 1 : colEnd;
    rowEnd = rowEnd >= rows ? rows - 1 : rowEnd;

    for (var row = 0; row <= rowEnd; row++) {
      for (var col = 0; col <= colEnd; col++) {
        ctx1.fillStyle = highlightColor;
        ctx1.fillRect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }



    // Display the selection info
    $('#showInfo').text('Selected Rows: ' + (rowEnd + 1) + ', Columns: ' + (colEnd + 1));
    
    return { rows: rowEnd + 1, columns: colEnd + 1 };
  }
  
 



    // 监听按钮点击事件
    document.getElementById('show_insert_table').addEventListener('click', function(event) {
    const button = event.currentTarget;
    const canvas = document.getElementById('canvasPopup');
    const buttonRect = button.getBoundingClientRect();

    // 设置 canvas 位置在按钮的左下方
    canvas.style.top = buttonRect.bottom + window.scrollY + 'px'; // 添加滚动偏移
    canvas.style.left = buttonRect.left + window.scrollX + 'px'; // 添加滚动偏移

    // 切换 canvas 的显示状态
    canvas.style.display = (canvas.style.display === 'block') ? 'none' : 'block';

    // 绘制格子，如果 canvas 已显示
    if (canvas.style.display === 'block') {
     // drawGrid(canvas);
     drawGrid(); // Initial grid draw
    }
  });
  
// 传入边距值和行列数来绘制表格
  // 假设用户输入的边距值为10mm
  var marginTop = 10; // 上边距
  var marginBottom = 10; // 下边距
  var marginLeft = 10; // 左边距
  var marginRight = 10; // 右边距
  
  // 假设上次选中的行列数
  var lastSelectedRows = 0;
  var lastSelectedCols = 0;
/*
"cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
*/

  function generateJsonData(rows, columns) {
    if(rows==0||columns==0)
    return;
   var cellWidth=720/columns;
   var cellHeight=32;
   var temp_offsetX=0;
   var temp_offsetY=0;
   jsonData = [];
  for (var i = 0; i < rows; i++) {
    var row = { "cells": [] };
    for (var j = 0; j < columns; j++) {
    
      // row.cells.push({ "content": String.fromCharCode(65 + j) + (i + 1), 
      row.cells.push({ "content": "", 
      "x":temp_offsetX,"y":temp_offsetY,"width": cellWidth, "height": cellHeight, 
      "borderSize": 1, "showBorder": true ,"selected": false,
       "rowspan":0, "colspan":0,
       "parentRow":-1,"parentCol":-1,
       "mWidth":0,"mHeight":0,
       "textAlign": 0,
       "hasCheckBox":false,"checkStatus":false,
       "borderStyle":'solid',
       "borderWidth": '1px',
       "borderColor": 'black',                
       "verticalAlign":1, 
       "fontSize":16,                     
       "indent": 0,
       "bold": false,
       "italic": false,
       "underline": false,
       "underlineColor": "rgb(255, 0, 0)",
       "backgroundColor": "transparent",
       "underlineStyle": "wavy",
       "strikethrough": false,
       "color": "rgb(0, 0, 0)"      
      
      });
      temp_offsetX+=cellWidth;  
    }
    temp_offsetY+=cellHeight
    temp_offsetX=0;
    jsonData.push(row);
  }
  return jsonData;
}

  // Mousedown event to confirm selection and hide the first layer
  

  function drawTableOnLayer2WithMargins(rows, cols, marginTop, marginBottom, marginLeft, marginRight) {
    var canvas2 = document.getElementById('myCanvas');
    var ctx2 = canvas2.getContext('2d');
    var a4WidthPixels = 793; // A4宽度，单位为像素
    var a4HeightPixels = 1122; // A4高度，单位为像素
  
    // 边距转换为像素，这里假设边距是以毫米为单位输入的
    var marginTopPixels = marginTop * 3.78;
    var marginBottomPixels = marginBottom * 3.78;
    var marginLeftPixels = marginLeft * 3.78;
    var marginRightPixels = marginRight * 3.78;
  
    // 计算可用于表格的宽度和高度
    var usableWidth = a4WidthPixels - marginLeftPixels - marginRightPixels;
    var usableHeight = 40*3.78*rows;//a4HeightPixels - marginTopPixels - marginBottomPixels;
  
    // 根据可用宽度和高度计算单元格的宽度和高度
    var cellWidth = usableWidth / cols;
    var cellHeight = 40;//usableHeight / rows;
  
    // 清除之前的绘制
    ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  
    // 开始绘制表格
    ctx2.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < cols; col++) {
        ctx2.rect(marginLeftPixels + col * cellWidth, marginTopPixels + row * cellHeight, cellWidth, cellHeight);
      }
    }
    ctx2.strokeStyle = 'black';   // 设置线条颜色
    ctx2.stroke();                // 绘制表格线条
  }

//编辑器状态管理器
  var editorState = {
    currentObject: {
        type: null,
        id: null,
    },
    cell: {},
    textBox: {},
    image: {},
    control: {},
    dialog: {},
    updateObject: function(type, id, properties) {
        if (!this[type]) {
            console.error('Unsupported type:', type);
            return;
        }
        if (!this[type][id]) {
            this[type][id] = {};
        }
        this[type][id] = { ...this[type][id], ...properties };
        this.setCurrentObject(type, id);
    },
    setCurrentObject: function(type, id) {
        this.currentObject.type = type;
        this.currentObject.id = id;
    },
    getCurrentObject: function() {
        const { type, id } = this.currentObject;
        if (type && id && this[type] && this[type][id]) {
            return this[type][id];
        }
        return null;
    }
};

// 初始化单元格对象
editorState.updateObject('cell', 'cell1', {
    borderStyle: 'solid',
    borderWidth: '1px',
    borderColor: 'black',
    textAlign: 'center',
    verticalAlign: 'middle'
});
  
  


  $(document).ready(function() {


    checkedBoxImage = new Image();
    checkBoxImage = new Image();

    // 定义一个创建图片加载Promise的函数，接受图片对象和图片路径作为参数
    function loadImage(image, src) {
        return new Promise((resolve, reject) => {
            $(image).on('load', resolve).on('error', () => reject(`Failed to load image at ${src}`));
            image.src = src;
        });
    }

    // 使用Promise.all等待所有图片都加载成功
    Promise.all([
        loadImage(checkedBoxImage, 'imgs/checked_box.png'),
        loadImage(checkBoxImage, 'imgs/check_box.png')
    ]).then(() => {
        console.log('所有图片加载成功');
        // 所有图片加载成功后的操作
        redraw();
    }).catch((error) => {
        console.log(error); // 打印出失败的图片
        // 处理图片加载失败的情况
    });


    var selectFontColor_colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#000000', '#FFFFFF',
              '#C0C0C0', '#808080', '#800000', '#808000', '#008000', '#800080', '#008080', '#000080',
              '#FFA500', '#A52A2A', '#FFFFF0', '#F0E68C', '#6495ED', '#DC143C', '#FFD700', '#ADFF2F'];

  
    var selectFontColor_dialog = $('<div></div>').appendTo('body').hide();
    for(var i = 0; i < selectFontColor_colors.length; i++) {
        $('<div></div>')
            .addClass('selectFontColor_color-button')
            .css('background-color', selectFontColor_colors[i])
            .appendTo(selectFontColor_dialog)
            .click(function() {
                var color = $(this).css('background-color');
                console.log("A2 selectFontColor:"+color);
                selectFontColor_dialog.dialog('close');

                const cell = getCellByCoords(selectionStartX, selectionStartY);
                if(cell!=null)
                {
                  
                  cell.color=color;
                  console.log("A2: cell.color click: 1"+cell.color);

                  redraw();
                  return;
                }
               
            });
    }

    selectFontColor_dialog.dialog({
        autoOpen: false,
        title: '选择颜色'
    });

    $('#set_fontcolor').click(function(e) {
        var x = e.pageX;
        var y = e.pageY;

        selectFontColor_dialog.dialog("option", "position", {
            my: "left top",
            at: "left+" + x + " top+" + y,
            of: window,
            collision: "fit"
        });

        selectFontColor_dialog.dialog('open');
    });

 // 字体选项数组
      // var fontOptions = [
      //     "思源黑体",
      //     "思源宋体",
      //     "思源柔黑",
      //     "思源真黑",
      //     "方正仿宋简体",
      //     "方正黑体简体"
      // ];

      var fontOptions = [
          "黑体",
          "宋体",
          "仿宋",
          "楷体",
          "方正仿宋简体",
          "方正黑体简体"
      ];

      // 将字体选项添加到下拉框中
      $.each(fontOptions, function(index, font) {
          $('#fontSelector').append('<option value="' + font + '">' + font + '</option>');
      });

      $('#fontSelector').change(function() {
          var selectedFont = $(this).val();
          console.log("A1 当前选中的字体是：" + selectedFont);

          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            cell.font=selectedFont;
            console.log("A1: cell.selectFont click: 1"+cell.font);
          }
          redraw();
          return;
          // 修改页面元素的字体样式
          $('body').css('font-family', selectedFont);
      });
      


        // 常用字体大小数组
  var fontSizes = [8, 12, 14, 16, 18, 20, 24, 32, 48];

// 将字体大小选项添加到下拉框中
$.each(fontSizes, function(index, size) {
    $('#fontSizeSelector').append('<option value="' + size + '">' + size + '</option>');
});



$('#fontSizeSelector').change(function() {
        
    var selectedSize = $('#fontSizeSelector').val();
    console.log("A3 当前选中的字体大小是：" + selectedSize);
    const cell = getCellByCoords(selectionStartX, selectionStartY);
        if(cell!=null)
        {
          if(selectedSize<64)
          cell.fontSize=parseInt(selectedSize);
          console.log("A3: cell.selectedSize click: 1"+cell.selectedSize);
        }
        redraw();
        return;
      });


     /*
    "text-align":0
	   单元格对齐方： 
     0 水平左对齐   1 水平居中  2 水平右对齐   3 垂直顶部对齐  4 垂直居中对齐  5 垂直底部对齐 6 
    */
    $('.menu-item').click(function() {
        var action = $(this).data('action'); // 使用jQuery的.data()方法获取data-action值
        console.log('Clicked button action:', action);

        if(action=="left_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=0;
            console.log("A1: align click: 0"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="midd_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=1;
            console.log("A1: align click: 1"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="right_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=2;
            console.log("A1: align click: 2"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="justify_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=3;
            console.log("A1: align click: 3"+cell.content);
          }
          redraw();
          return;
        }


        if(action=="valign_top")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=0;
            console.log("A1: click: 0"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="valign_midd")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=1;
            console.log("A1: click: 1"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="valign_bottom")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=2;
            console.log("A1: click: 0"+cell.content);
          }
          redraw();
          return;
        }


        if(action=="addindent")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.indent=cell.indent+1;
            console.log("A1: indent click: 1"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="minusindent")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            if(cell.indent>0)
            cell.indent=cell.indent-1;
            console.log("A1: indent click: 2"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="incFontSize")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            console.log("A3: cell incFontSize: "+cell.fontSize);
            if(cell.fontSize<64)
            cell.fontSize=parseInt( cell.fontSize)+1;
            console.log("A3: 加一后 cell incFontSize: "+cell.fontSize);

             if(cell.fontSize>64)
             cell.fontSize=64;
            console.log("A3: incFontSize click: 2"+cell.content);
          }
          redraw();
          return;
        } 

       if(action=="minFontSize")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          { console.log("A3: cell minFontSize: "+cell.fontSize);
            if(cell.fontSize>12)
            cell.fontSize=parseInt( cell.fontSize)-1;
            console.log("A3: minFontSize click: 2 "+cell.content);
          }
          redraw();
          return;
        }

        

        if(action=="setBold")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            cell.bold=!cell.bold;
            console.log("A1: cell.bold click: 1"+cell.content);
          }
          redraw();
          return;
        }




        if(action=="italicOn")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            cell.italic=!cell.italic;
            console.log("A1: cell.italic click: 1"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="underLine")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            cell.underline=!cell.underline;
            cell.strikethrough=false;
            console.log("A1: cell.underline click: 1"+cell.content+ " hasUnderLine:"+cell.underline);
          }
          redraw();
          return;
        }

        if(action=="deleteline")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            cell.strikethrough=!cell.strikethrough;
            cell.underline=false;
            console.log("A1: cell.strikethrough click: 1"+cell.content+ " has strikethrough:"+cell.strikethrough);
          }
          redraw();
          return;
        }

   
  


        $('#selectLineColor_openDialog').click(function(event) {
        var dialog = $('#selectLineColor_dialog');
        var x = event.clientX;
        var y = event.clientY;
        var dialogWidth = dialog.outerWidth();
        var dialogHeight = dialog.outerHeight();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();

        // Adjust if the dialog goes beyond the right edge
        if (x + dialogWidth > windowWidth) {
          x -= (x + dialogWidth - windowWidth);
        }

        // Adjust if the dialog goes beyond the bottom edge
        if (y + dialogHeight > windowHeight) {
          y -= (y + dialogHeight - windowHeight);
        }

        // Adjust if the dialog goes beyond the left edge
        if (x < 0) {
          x = 0;
        }

        // Adjust if the dialog goes beyond the top edge
        if (y < 0) {
          y = 0;
        }

        dialog.css({'left': x + 'px', 'top': y + 'px', 'display': 'block'});
      });



      $('#selectLineColor_dialog').click(function(event) {
        if ($(event.target).is('button')) {
          console.log("A1 buttonID:"+event.target.id);
          $('#selectLineColor_dialog').hide();

            const cell = getCellByCoords(selectionStartX, selectionStartY);
            if(cell!=null)
            {
              
            
              if(event.target.id=="selectLineColor_black")
              cell.underlineColor='rgb(0, 0, 0)';
              if(event.target.id=="selectLineColor_green")
              cell.underlineColor='rgb(0, 255, 0)';
              if(event.target.id=="selectLineColor_red")
              cell.underlineColor='rgb(255, 0, 0)';
              if(event.target.id=="selectLineColor_noColor")
              cell.underlineColor='transparent';
              console.log("A1: cell.underlineColor click: 1"+cell.content+ " underlineColor:"+cell.underlineColor);
            }
            redraw();
            return;

        }
      });



        if(action=="backgroundColor")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            if('rgb(211, 211, 211)'==cell.backgroundColor)
            cell.backgroundColor="transparent";
           else
           cell.backgroundColor='rgb(211, 211, 211)';
            console.log("A1: cell.underline click: 1"+cell.content+ " hasUnderLine:"+cell.underline);
          }
          redraw();
          return;
        }


      


        

        

    });

    $('#selectLineStyle_openDialog').click(function(event) {
        var dialog = $('#selectLineStyle_dialog');
        var x = event.clientX;
        var y = event.clientY;
        var dialogWidth = dialog.outerWidth();
        var dialogHeight = dialog.outerHeight();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();

        // Adjust if the dialog goes beyond the right edge
        if (x + dialogWidth > windowWidth) {
          x -= (x + dialogWidth - windowWidth);
        }

        // Adjust if the dialog goes beyond the bottom edge
        if (y + dialogHeight > windowHeight) {
          y -= (y + dialogHeight - windowHeight);
        }

        // Adjust if the dialog goes beyond the left edge
        if (x < 0) {
          x = 0;
        }

        // Adjust if the dialog goes beyond the top edge
        if (y < 0) {
          y = 0;
        }

        dialog.css({'left': x + 'px', 'top': y + 'px', 'display': 'block'});
      });

      $('#selectLineStyle_dialog').click(function(event) {
        if ($(event.target).is('button')) {
          console.log(event.target.id);
          var mySelectLineStyle="";

  

          if(event.target.id=="selectLineStyle_straightLine")
          {
            console.log("style:0");
            mySelectLineStyle='straight';

          }
          if(event.target.id=="selectLineStyle_doubleLine")
          {
            console.log("style:1");
            mySelectLineStyle='double';

          }
          if(event.target.id=="selectLineStyle_wavyLine")
          {
            console.log("style:2");
            mySelectLineStyle='wavy';

          }

          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null&&mySelectLineStyle!="")
          {
            
            cell.underlineStyle=mySelectLineStyle;            
            console.log("A1: cell.bold click: 1"+cell.content);
          }


          $('#selectLineStyle_dialog').hide();
          redraw();
          return;
        }
      });
   

    var cellData = {
        width: 200,
        height: 50,
        borders: {
            top: 'solid',
            right: 'solid',
            bottom: 'solid',
            left: 'solid'
        }
    };

    function updateCellStyle() {
        var cellEdge = $('#cell-edge');
        cellEdge.css({
            'border-top': '3px ' + cellData.borders.top + ' black',
            'border-right': '3px ' + cellData.borders.right + ' black',
            'border-bottom': '3px ' + cellData.borders.bottom + ' black',
            'border-left': '3px ' + cellData.borders.left + ' black',
        });
    }

    $('#cell-edge').click(function(event) {
        var this2 = $(this);
        var width = this2.width();
        var height = this2.height();
        var offsetX = event.pageX - this2.offset().left;
        var offsetY = event.pageY - this2.offset().top;

        // Determine which edge is clicked based on mouse position
        if (offsetX < 10) cellData.borders.left = cellData.borders.left === 'solid' ? 'dashed' : 'solid';
        else if (width - offsetX < 10) cellData.borders.right = cellData.borders.right === 'solid' ? 'dashed' : 'solid';
        else if (offsetY < 10) cellData.borders.top = cellData.borders.top === 'solid' ? 'dashed' : 'solid';
        else if (height - offsetY < 10) cellData.borders.bottom = cellData.borders.bottom === 'solid' ? 'dashed' : 'solid';

        updateCellStyle();
        console.log(cellData);
    });

    $('#setCell').button().on('click', function() {
        $('#cell-dialog').dialog({
            modal: true,
            width: 300,
            height: 250,
            open: function(event, ui) {
                updateCellStyle();
            }
        });
    });

    $('#cancel-button').click(function() {
        console.log("Cancel button pressed");
        $('#cell-dialog').dialog("close");
    });

    $('#confirm-button').click(function() {
        console.log("Confirm button pressed");
        $('#cell-dialog').dialog("close");
    });



// 预加载图片
// var checkedBoxImage = new Image();
// checkedBoxImage.src = 'imgs/checked_box.png';

// var checkBoxImage = new Image();
// checkBoxImage.src = 'imgs/check_box.png';

    jsonData={};
    jsonData =my_jsonData;
   
//show_subTab_manager
//处理分表管理
var data = {
    "tables": [
      {
        "id": 1,
        "name": "A表",
        "rows": [
          {"id": 1, "rowNum": 11},
          {"id": 2, "rowNum": 12},
          {"id": 3, "rowNum": 13}
        ]
      },
      {
        "id": 2,
        "name": "B表",
        "rows": [
          {"id": 1, "rowNum": 14},
          {"id": 2, "rowNum": 15},
          {"id": 3, "rowNum": 16}
        ]
      }
    ]
  };

  var currentOperation = { type: 'add', tableId: null };

  $("#show_subTab_manager").on("click", function() {
    $("#mag_tab_dialog").dialog({
      width: 900,
      modal: true,
      open: function(event, ui) {
        fillTable1();
      }
    });
  });

  $("#mag_tab_add-table").on("click", function() {
    currentOperation = { type: 'add', tableId: null };
    $("#mag_tab_add-subtable-dialog").dialog("option", "title", "增加子表").dialog("open");
    $("#mag_tab_subtableName").val('');
  });

  $("#mag_tab_add-subtable-dialog").dialog({
    autoOpen: false,
    width: 600,
    modal: true
  });

  $("#mag_tab_confirm-add-subtable").on("click", function() {
    var subtableName = $("#mag_tab_subtableName").val().trim();

    if (subtableName) {
      if (currentOperation.type === 'add') {
        var newTableId = new Date().getTime();
        data.tables.push({
          "id": newTableId,
          "name": subtableName,
          "rows": []
        });
        fillTable1();
      } 
      
      if (currentOperation.type === 'edit'){
        var table = data.tables.find(t => t.id === currentOperation.tableId);
        if (table) {
          table.name = subtableName;
        }
        fillTable1();
      }
     





      var inputVal = $("#mag_tab_subtableName").val().trim();
    if (!inputVal) {
        alert("名称不能为空！");
        return;
    }
    if (currentOperation.type === 'addRow') {
        var table = data.tables.find(t => t.id === currentOperation.tableId);
        if (table) {
            var newRowId = new Date().getTime(); // 简单的ID生成策略
            table.rows.push({ "id": newRowId, "rowNum": parseInt(inputVal, 10) });
            fillTable2(table.rows); // 更新table2以显示新增的行
        }
    }

      $("#mag_tab_add-subtable-dialog").dialog("close");
    } else {
      alert("子表名不能为空！");
    }
  });

  function fillTable1() {
    var tbody = $("#mag_tab_table1 tbody");
    tbody.empty();
    $.each(data.tables, function(i, table) {
        var seqNum = i + 1;
        var deleteButton = $('<button>').text('删除').on('click', function(e) {
            e.stopPropagation(); // 防止点击删除按钮时触发行点击事件
            data.tables = data.tables.filter(t => t.id !== table.id);
            fillTable1();
            $("#mag_tab_table2 tbody").empty(); // 清除table2的内容
        });
        var editButton = $('<button>').text('修改').on('click', function(e) {
            e.stopPropagation(); // 防止点击修改按钮时触发行点击事件
            currentOperation = { type: 'edit', tableId: table.id };
            $("#mag_tab_add-subtable-dialog label").text("子表名称："); // 修改标签文本
            $("#mag_tab_subtableName").val(table.name);
            $("#mag_tab_add-subtable-dialog").dialog("option", "title", "修改子表名").dialog("open");
        });

        var addRowButton = $('<button>').text('增加行').on('click', function(e) {
        e.stopPropagation(); // 防止触发行点击事件
        currentOperation = { type: 'addRow', tableId: table.id };
        $("#mag_tab_subtableName").val(''); // 清空输入值
        $("#mag_tab_add-subtable-dialog").dialog("option", "title", "增加行"); // 修改对话框标题
        $("#mag_tab_add-subtable-dialog label").text("行号："); // 修改标签文本
        $("#mag_tab_add-subtable-dialog").dialog("open"); // 打开对话框
        });
        // 创建表格行
        var tr = $("<tr>")
            .append(
                $("<td>").text(seqNum),
                $("<td>").text(table.name),
                $("<td>").append(deleteButton),
                $("<td>").append(editButton),
                $("<td>").append(addRowButton)
            )
            .on('click', function() { // 为行添加点击事件
                $("#mag_tab_table1 tr").removeClass("mag_tab_highlighted");
                $(this).addClass("mag_tab_highlighted");
                fillTable2(table.rows); // 根据点击的行填充table2
            });

        tbody.append(tr);
    });
}
function fillTable2(rows) {
    var tbody = $("#mag_tab_table2 tbody");
    tbody.empty();
    $.each(rows, function(i, row) {
        var seqNum = i + 1; // 序号从1开始

        var deleteButton = $('<button>').text('删除').on('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡到行点击事件

            // 从当前分表中删除选中的行
            var currentTableRows = data.tables.find(table => table.rows.some(r => r.id === row.id)).rows;
            var rowIndex = currentTableRows.findIndex(r => r.id === row.id);
            if (rowIndex > -1) {
                currentTableRows.splice(rowIndex, 1);
            }

            fillTable2(currentTableRows); // 重新填充table2来显示更新后的数据
        });

        var tr = $("<tr>")
            .append($("<td>").text(seqNum), $("<td>").text(row.rowNum), $("<td>").append(deleteButton))
            .on('click', function() {
                // 在点击时添加或移除高亮效果
                $("#mag_tab_table2 tr").removeClass("mag_tab_highlighted"); // 先移除其他行的高亮
                $(this).addClass("mag_tab_highlighted"); // 为点击的行添加高亮
            });

        tbody.append(tr);
    });
}

//处理分表管理完成 

 // 切换一级菜单显示
 $('#Main_File_fileButton').on('click', function(event){
        $('#Main_File_fileMenu').toggle();
        event.stopPropagation();
    });

    // 二级菜单显示
    $('#Main_File_fileMenu > li').has('ul').hover(function(){
       $(this).children('.Main_File_submenu').stop(true, true).fadeIn(100);
    }, function(){
        $(this).children('.Main_File_submenu').stop(true, true).fadeOut(100);
    });

    // 点击其他地方关闭所有菜单
    $(document).on('click', function(){
        $('#Main_File_fileMenu').hide();
        $('.Main_File_submenu').hide();
    });

    // 防止菜单内部点击时菜单关闭
    $('#Main_File_fileMenu').on('click', function(event){
        event.stopPropagation();
    });
    


    $('#myCanvas').click(function(e) {
    const rect = this.getBoundingClientRect();
    var x = e.clientX - rect.left - window.scrollX; // 考虑水平滚动
    var y = e.clientY - rect.top - window.scrollY; // 考虑垂直滚动

    var cursorX = event.pageX;
    var cursorY = event.pageY;
    x=cursorX;
    y=cursorY;

 		console.log("good girl------------------");
    var canvasOffset = $('#myCanvas').offset(); 


    var cellStartX = canvasOffset.left+tableOffsetX;
    var cellStartY = canvasOffset.top+tableOffsetY;
    

    console.log("mouseX:" ,x,"mouseY:", y,"cellStart_x:",cellStartX,"cellStart_Y:",cellStartY);
    jsonData.forEach(row => {
      row.cells.forEach(cell => {

          var cell_X = cellStartX + cell.x;
          var cell_Y = cellStartY + cell.y;  

          console.log("cellX:" ,cell_X,"cellY:" ,cell_Y);
        if (x > cell_X && x < cell_X + cell.width && y > cell_Y && y < cell_Y + cell.height) {
          
          let input = $('#text-input');
          console.log(cell.x+" <-x y-> "+ cell.y)
          input.val(cell.content);
          console.log(cell.content+" cell.y="+cell.y);
          cell.content="";

          var checkBoxX=0;
          var checkBoxY=0;

          if (cell.hasCheckBox) {
        
          // 请根据你的图片实际大小调整这里的偏移和位置
           checkBoxX =  45; // 举例，复选框距单元格左边界10像素
           
         
        }


          if(cell.rowspan>0||cell.colspan>0)
          {
            input.css({
                    display: 'block',
                    left: cell_X+checkBoxX,
                    top: cell_Y ,
                    width: cell.mWidth-checkBoxX,
                    height: cell.mHeight
                 }).focus();

          }
          else
          {
            input.css({
                    display: 'block',
                    left: cell_X+checkBoxX,
                    top: cell_Y ,
                    width: cell.width-checkBoxX,
                    height: cell.height
                 }).focus();
          }
     
          if (cell.hasCheckBox) {
                        
                        cell.checkStatus = !cell.checkStatus; // 切换复选框状态
                       ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
                     
                    }

                 //drawTable(jsonData);
          
          input.off('blur').on('blur', function() {
            cell.content = this.value;
            input.hide();
            //drawTable(jsonData);
          });
        }
      });
    });

    redraw();
  });



    $(".menu").click(function(){
        
        // 移除所有菜单项的.active类
          $(".menu").removeClass("active");
        // 为当前被点击的菜单项添加.active类
        $(this).addClass("active");

        
        console.log("your click:"+$(this).attr("data-target"));

        var clickMenuId=$(this).attr("data-target");

        var targetSelector = "#" + $(this).attr("data-target");
        
        var targetId = $(this).attr("data-target"); // 获取ID或类的名称
        $(".submenu2").hide(); // 隐藏所有子菜单
        $(".submenu").hide(); // 隐藏所有子菜单
        if(clickMenuId=="Files")
        {
          console.log("hello girl");
          return;
        }

        if(clickMenuId=="start")
        {        
         
          $("#" + targetId).toggle(); // 直接使用ID选择器
          $(".submenu-container").show();
          
         // $('.submenu div').attr('style', 'display: block;');
        }        
        else 
        {
         
          $("#" + targetId).toggle(); // 直接使用ID选择器
          $(".submenu-container").show();
        }
        
       

        
    	




    });

    // $(".submenu div").hover(
    //     function(){
    //         $(this).css("background-color", "lightblue");
    //     }, 
    //     function(){
    //         $(this).css("background-color", "white");
    //     }
    // );

        // 默认显示“开始”菜单的二级菜单，同时为其添加.active类高亮显示
    var startMenu = $("#start");
    startMenu.show();
    $(".submenu-container").show(); // 确保容器是可见的	
	  $("[data-target='start']").addClass("active"); // 高亮“开始”菜单项


 function saveState() {
     // 这里使用深复制来保存当前状态
     historyStack.push(JSON.parse(JSON.stringify(jsonData)));
     redoStack = []; // Clear the redo stack after a new action
 }
 
 function undo() {
     if (historyStack.length > 0) {
         redoStack.push(JSON.parse(JSON.stringify(jsonData)));
         jsonData = historyStack.pop();
         redraw()
		 console.log("-=========undo()===========");
     }
 }
 
 function redo() {
     if (redoStack.length > 0) {
         historyStack.push(JSON.parse(JSON.stringify(jsonData)));
         jsonData = redoStack.pop();
         redraw()
		 console.log("-=========redo()===========");
     }
 }
function addRow()
{

// 步骤1&2: 选择并复制jsonData中最后一个cells元素组
var newCellsGroup = JSON.parse(JSON.stringify(jsonData[jsonData.length - 1].cells));

// 步骤3: （可选）修改新复制的cells元素组的属性，比如根据需要调整x或y属性
var lastCellY=0;
//获取表格的总高度，作为最后一行表格的y坐标
jsonData.forEach(function(row) {
    // 找到每行的最后一个单元格
    var lastCell = row.cells[row.cells.length - 1];
    lastCellY=lastCell.y+lastCell.height;

});

newCellsGroup.forEach(function(cell) {
    cell.y = lastCellY; // 假设每个cell的高度为40，这里我们简单地将y增加40以移动到新的行
    cell.showBorder=true;
    cell.hasCheckBox=false;
    cell.selected=false;
    cell.hasCheckBox= false,
    checkStatus=false,
    cell.selected= false,
    cell.borderStyle= "solid",
    cell.borderWidth="1px",
    cell.borderColor="black",
    cell.verticalAlign= 0,
    cell.fontSize=22,
    cell.indent= 0,
    cell.bold=false,
    cell.italic= false,
    cell.underline=false,
    cell.underlineColor="rgb(255, 0, 0)",
    cell.backgroundColor="transparent",
    cell.underlineStyle="wavy",
    cell.strikethrough= false,
    cell.color="rgb(0, 0, 0)",
    cell.content=""
});

// 步骤4: 将复制并可能已修改的cells元素组添加到jsonData数组的末尾
jsonData.push({cells: newCellsGroup});
//updateForSellMerging()
  saveState();
    
        drawTable();

  console.log("-=========add row()===========");
}

function addCol()
{

// 遍历jsonData中的每个元素（每行）
jsonData.forEach(function(row) {
    // 找到每行的最后一个单元格
    var lastCell = row.cells[row.cells.length - 1];
    
    // 复制最后一个单元格（深复制）
    var newCell = JSON.parse(JSON.stringify(lastCell));
    
    // 调整复制单元格的x值，使其位于行的最右侧
    // 新的x值是当前最后一个单元格的x值加上其宽度
    newCell.x = lastCell.x + lastCell.width;
    newCell.showBorder=true;
    
    // 将调整后的单元格添加到当前行
    row.cells.push(newCell);
  

});
  updateForSellMerging()
 
  saveState();
    
        drawTable();

  console.log("-=========add row()===========");
}
$("#MergeCells").click(doSellMerging);
$("#splitCells").click(doSellSplit);
 $("#undo").click(undo);
 $("#redo").click(redo);
 $("#addRow").click(addRow);
 $("#addCol").click(addCol);

 function doSellSplit()
 {

  highlightButton('splitCells', 0);
  highlightButton('MergeCells', 0);
      
  console.log('表格选择鼠标左键被释放。');
        var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		var canvasOffset = canvas.offset();

	    

        //查询是否有需要合并的单元格,如果有就弹出菜单
         var hasMoreThanOneCellSelected = 0;
         var selectedRow=0;
         var selectedCol=0;

         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {           
             if( cell.selected ==true)
             {
              selectedRow=rowIndex;
              selectedCol=cellIndex;

              hasMoreThanOneCellSelected++;
              
              console.log("A4 selecteded cell row:"+rowIndex+" index = " + cellIndex +" rowSpan = " + 

              cell.rowspan+" cell col Span = " + cell.colspan+" cellwidth="+cell.width+

              " cellheight="+cell.height+" cell.mwidth ="+cell.mWidth+ "cell.mHeidht="+cell.mHeight);
       
                 var tempRowspan=cell.rowspan

                 console.log("A4 for(var j= "+rowIndex+ ";j<="+(rowIndex+tempRowspan)+" ;j++)");
                for( var j=rowIndex;j<=(rowIndex+tempRowspan);j++ )//处理单列，一行一行的处理
                {
                  //拆分列时，每列的高度要重新计算，与相邻的单元格高度一致
                  var tempCellHeight=0;
                  if(cellIndex>0)  //非第一列，将首列的行高取出，备用。
                  {
                    tempCellHeight=jsonData[j].cells[cellIndex-1].height; //同一行前一列的高
                  }
                  else
                  {  //当前列是第一列，即是0列下标。要找下一列
                    console.log("A4 if(cells.lenght{"+rowData.cells.length+"} >=(cellIndex+1){"+(cellIndex+1)+"}");
                    
                    if(rowData.cells.length>=cellIndex+1)
                    tempCellHeight=jsonData[j].cells[cellIndex+1].height; //同一行前一列的高
                  }
                  var offsetY=0;
                  for(var yy=0;yy<rowIndex;yy++)
                  {
                    offsetY+=jsonData[yy].cells[cellIndex].height;
                  }
                  var netxCellRow=rowIndex+tempRowspan;
                
                  console.log("A4 单列处理----》处理单列j:"+j+"  rowIndex:"+rowIndex+" rowIndex+cell.rowspan:"+netxCellRow+" cellIndex:"+cellIndex+" cell rowspan = " + tempRowspan);
                  jsonData[j].cells[cellIndex].showBorder = true;
                  jsonData[j].cells[cellIndex].parentRow=-1;
                  jsonData[j].cells[cellIndex].parentCol=-1;
                  jsonData[j].cells[cellIndex].rowspan=0;
                  jsonData[j].cells[cellIndex].colspan=0;
                  
                  jsonData[j].cells[cellIndex].height=tempCellHeight
                  jsonData[j].cells[cellIndex].mHeight=tempCellHeight;
                  jsonData[j].cells[cellIndex].y=offsetY;
                }

                var tempColspan=cell.colspan
                for( var i=cellIndex;i<=cellIndex+tempColspan;i++)//处理单行，一列一列的处理
                {
                  console.log("A4 处理行单行:"+cellIndex+"处理列："+i);
                  jsonData[selectedRow].cells[i].showBorder = true;
                  jsonData[selectedRow].cells[i].parentCol=-1;
                  jsonData[selectedRow].cells[i].parentRow=-1;
                  jsonData[selectedRow].cells[i].rowspan=0;
                  jsonData[selectedRow].cells[i].colspan=0;

                }

                for( var i=rowIndex;i<=rowIndex+tempRowspan;i++)
                {
             

                for( var j=cellIndex;j<=cellIndex+tempColspan;j++ )
                  {
                    console.log("A4 处理行："+i+"处理列:"+j)+" showBorder:";
                    jsonData[i].cells[j].showBorder = true;
                    jsonData[i].cells[j].parentRow=-1;
                    jsonData[i].cells[j].parentCol=-1;
                    jsonData[i].cells[j].selected=true;
                    jsonData[i].cells[j].rowspan=0;
                    jsonData[i].cells[j].colspan=0;
                  }
                }  

             }

           
            
        });
      });
      jsonData[selectedRow].cells[selectedCol].rowspan = 0;
      jsonData[selectedRow].cells[selectedCol].colspan = 0;
      // jsonData[selectedRow].cells[selectedCol].mHeight = 0;
      // jsonData[selectedRow].cells[selectedCol].mWidth = 0;
      updateForSellMerging();
      saveState();
	 
     redraw();
      return;

        //查询是否有需要合并的单元格,如果有就弹出菜单
        // if(hasMoreThanOneCellSelected>1)
        //  drawMenu(x, y);

        console.log('合并单元格 数量：'+hasMoreThanOneCellSelected);
         

         // Merge selected cells
         const selectedCells = [];
         const mergedCells = []; //记录要合并的单元行号与列号
    
       
           jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               { 
                   if (cell.selected) 
                  {
                    cell.row=0;
                    cell.col=0;

            
                   selectedCells.push(cell);//
                   mergedCells.push(cell); 
                   console.log("-=========selectedCells======将已选的单元格汇总 ====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列 content:"+cell.content);
                  }
                   n++;
               });

               console.log("----------");
              
         });
   
         
   
   
       if(selectedCells.length > 1) {
  
       const minX = Math.min(...selectedCells.map(cell => cell.x));
       const minY = Math.min(...selectedCells.map(cell => cell.y));
       const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
       const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
       let mergedContent = "";

    
       console.log("要合并的后的单元格起点 X： "+String(minX)+ "  Y:"+String(minY));
       console.log("要合并的后的单元格终点 X： "+String(maxX)+ "  Y:"+String(maxY));


       const startCell = getCellByCoords(minX+2, minY+2);
       const startCellIndex=getCRFormCell(minX+2,minY+5,"计算跨行数取开始：");

      const endCellIndex=getCRFormCell(maxX-5,maxY-5,"计算跨行数取最大：");


       console.log("合并单元格 startCellIndex :"+startCellIndex.row +" <=>  "+startCellIndex.col);

       selectedCells.forEach(cell => {
         mergedContent = " "; // Concatenate the content of selected cells
         cell.showBorder = true;
     
         console.log("要合并的=第 "+String(cell.content));
         cell.content = ""; // Clear the content of the cell after merging
       });
   
   

       var cellRowSpan=0;
       var cellColSpan=0;
  
      // console.log("合并单元格开始行号:"+startCellIndex.row+"  列号:"+String(startCellIndex.col));
      // console.log("合并单元格 结束行号:"+endCellIndex.row);
      // console.log("合并单元格 结束列号:"+endCellIndex.col);

      cellRowSpan=endCellIndex.row-startCellIndex.row+1;
      cellColSpan=endCellIndex.col-startCellIndex.col+1;
      // console.log("合并单元格 跨行数 rowspan："+cellRowSpan);
      // console.log("合并单元格 跨列数 colspan："+cellColSpan);

       			//将被合并的单元格作合并
       			mergedCells.forEach(cell=>{

								//console.log("-=========mergedCells===第 "+String(cell.row)+" 行 第:"+String(cell.col)+"列 content:"+cell.content+" startCellIndex.row="+String(startCellIndex.row)+" endCellIndex.col="+String(startCellIndex.col));
                if(startCellIndex.row == cell.row && startCellIndex.col == cell.col)
                {
                  //给父亲单元格记录跨行 跨列的数值
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  jsonData[cell.row].cells[cell.col].rowspan=0;
                  jsonData[cell.row].cells[cell.col].colspan=0;

                 // console.log("-=首行-----------------=");

                }
                else
                {
                  //给被合并的单元格，，记录父亲行列号，，
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  //console.log("-=非首行-----------------=");
                }
        
						}     
						)

       if (startCell) {
         startCell.mWidth  = maxX - minX;
         startCell.mHeight = maxY - minY;
         startCell.showBorder = true;
         startCell.rowspan=0;
         startCell.colspan=0;
         startCell.content = mergedContent.trim(); // Update the content of the start cell
         console.log("要合并的后的单元格 "+String(cell.content)+ "  X:"+String(minX)+ "  Y:"+String(minY)+" w:"+String(startCell.width)+" h:"+String(startCell.height)+" mWidth:"+String(startCell.mWidth)+" mHeight:"+String(startCell.mHeight));
         jsonData[startCellIndex.row].cells[startCellIndex.col].rowspan=0;
         jsonData[startCellIndex.row].cells[startCellIndex.col].colspan=0;
         updateCellSize(startCellIndex.row,startCellIndex.col,minX,minY,startCell.Width,startCell.Height);
       }
     }
   

     //从jsonData从最小的x开始遍历,找到最大的结束位
     var cellRowSpans=0; //单元格横跨单元格个数
    

   
     jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               {        
                  
                   console.log("合并后观察====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列  x: "+cell.x+"  y: "+cell.y+"  w: "+cell.width+"  h: "+cell.height+" parentRowIndex: "+cell.parentRow+"  parentColIndex: "+cell.parentCol," rowspan: "+cell.rowspan+" colspan: "+cell.colspan+" mWidth:"+String(cell.mWidth)+" mHeight:"+String(cell.mHeight)+" show:"+cell.showBorder);
                 
                   n++;
               });

               console.log("----------");
              
         });
   
     saveState();
	  console.log("===要合并的后的单元格saveState();")
     redraw();
     return;
     ///////////////////////合并完成

 }
 
 function doSellMerging()
 {

   

      highlightButton('MergeCells', 0);
      highlightButton('splitCells', 0);
        console.log('表格选择鼠标左键被释放。');
        var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		var canvasOffset = canvas.offset();
	    

        //查询是否有需要合并的单元格,如果有就弹出菜单
         var hasMoreThanOneCellSelected = 0;
         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {           
             if( cell.selected ==true)
             hasMoreThanOneCellSelected++;
        });
      });
       

        //查询是否有需要合并的单元格,如果有就弹出菜单
        // if(hasMoreThanOneCellSelected>1)
        //  drawMenu(x, y);

        console.log('合并单元格 数量：'+hasMoreThanOneCellSelected);
         

         // Merge selected cells
         const selectedCells = [];
         const mergedCells = []; //记录要合并的单元行号与列号
    
       
           jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               { 
                   if (cell.selected) 
                  {
                    cell.row=rowIndex;
                    cell.col=n;

            
                   selectedCells.push(cell);//
                   mergedCells.push(cell); 
                   console.log("-=========selectedCells======将已选的单元格汇总 ====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列 content:"+cell.content);
                  }
                   n++;
               });

               console.log("----------");
              
         });
   
         
   
   
       if(selectedCells.length > 1) {
  
       const minX = Math.min(...selectedCells.map(cell => cell.x));
       const minY = Math.min(...selectedCells.map(cell => cell.y));
       const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
       const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
       let mergedContent = "";

    
       console.log("要合并的后的单元格起点 X： "+String(minX)+ "  Y:"+String(minY));
       console.log("要合并的后的单元格终点 X： "+String(maxX)+ "  Y:"+String(maxY));


       const startCell = getCellByCoords(minX+2, minY+2);
       const startCellIndex=getCRFormCell(minX+2,minY+5,"计算跨行数取开始：");

      const endCellIndex=getCRFormCell(maxX-5,maxY-5,"计算跨行数取最大：");


       console.log("合并单元格 startCellIndex :"+startCellIndex.row +" <=>  "+startCellIndex.col);

       selectedCells.forEach(cell => {
         mergedContent += cell.content + " "; // Concatenate the content of selected cells
         cell.showBorder = false;
        //  cell.width = 0;
        //  cell.height = 0;
         console.log("要合并的=第 "+String(cell.content));
         cell.content = ""; // Clear the content of the cell after merging
       });
   
   

       var cellRowSpan=0;
       var cellColSpan=0;
  
      // console.log("合并单元格开始行号:"+startCellIndex.row+"  列号:"+String(startCellIndex.col));
      // console.log("合并单元格 结束行号:"+endCellIndex.row);
      // console.log("合并单元格 结束列号:"+endCellIndex.col);

      cellRowSpan=endCellIndex.row-startCellIndex.row+1;
      cellColSpan=endCellIndex.col-startCellIndex.col+1;
      // console.log("合并单元格 跨行数 rowspan："+cellRowSpan);
      // console.log("合并单元格 跨列数 colspan："+cellColSpan);

       			//将被合并的单元格作合并
       			mergedCells.forEach(cell=>{

								//console.log("-=========mergedCells===第 "+String(cell.row)+" 行 第:"+String(cell.col)+"列 content:"+cell.content+" startCellIndex.row="+String(startCellIndex.row)+" endCellIndex.col="+String(startCellIndex.col));
                if(startCellIndex.row == cell.row && startCellIndex.col == cell.col)
                {
                  //给父亲单元格记录跨行 跨列的数值
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  jsonData[cell.row].cells[cell.col].rowspan=cellRowSpan;
                  jsonData[cell.row].cells[cell.col].colspan=cellColSpan;

                 // console.log("-=首行-----------------=");

                }
                else
                {
                  //给被合并的单元格，，记录父亲行列号，，
                  jsonData[cell.row].cells[cell.col].parentRow=startCellIndex.row;
                  jsonData[cell.row].cells[cell.col].parentCol=startCellIndex.col;
                  //console.log("-=非首行-----------------=");
                }
        
						}     
						)

       if (startCell) {
         startCell.mWidth  = maxX - minX;
         startCell.mHeight = maxY - minY;
         startCell.showBorder = true;
         startCell.rowspan=endCellIndex.row-startCellIndex.row;
         startCell.colspan=endCellIndex.col-startCellIndex.col;
         startCell.content = mergedContent.trim(); // Update the content of the start cell
         console.log("要合并的后的单元格 "+String(cell.content)+ "  X:"+String(minX)+ "  Y:"+String(minY)+" w:"+String(startCell.width)+" h:"+String(startCell.height)+" mWidth:"+String(startCell.mWidth)+" mHeight:"+String(startCell.mHeight));
         jsonData[startCellIndex.row].cells[startCellIndex.col].rowspan=endCellIndex.row-startCellIndex.row;
         jsonData[startCellIndex.row].cells[startCellIndex.col].colspan=endCellIndex.col-startCellIndex.col;
         updateCellSize(startCellIndex.row,startCellIndex.col,minX,minY,startCell.mWidth,startCell.mHeight);
       }
     }
   

     //从jsonData从最小的x开始遍历,找到最大的结束位
     var cellRowSpans=0; //单元格横跨单元格个数
    

   
     jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               {        
                  
                   console.log("合并后观察====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列  x: "+cell.x+"  y: "+cell.y+"  w: "+cell.width+"  h: "+cell.height+" parentRowIndex: "+cell.parentRow+"  parentColIndex: "+cell.parentCol," rowspan: "+cell.rowspan+" colspan: "+cell.colspan+" mWidth:"+String(cell.mWidth)+" mHeight:"+String(cell.mHeight)+" show:"+cell.showBorder);
                 
                   n++;
               });

               console.log("----------");
              
         });
   
     saveState();
	  console.log("===要合并的后的单元格saveState();")
     redraw();
     return;
     ///////////////////////合并完成
 }
    $(document).on("contextmenu", function(e) {
    e.preventDefault(); // 阻止默认的右键菜单弹出
    });


$(menuCanvas).on('click', function(e) {
  const rect = menuCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  if (y > 30 && y < 50) 
  {
          console.log('合并单元格 clicked');
         

      // Merge selected cells
      const selectedCells = [];
 
  			jsonData.forEach(function(rowData, rowIndex) 
        {
    		    rowData.cells.forEach(function(cell) 
            {
     			     if (cell.selected) 
               {
        				selectedCells.push(cell);
                console.log("-=========selectedCells======将已选的单元格汇总===========");
                // 如果单元格有复选框，则切换选中状态
             
      		     }
 
            });
      });

  


    if(selectedCells.length > 1) {
    const minX = Math.min(...selectedCells.map(cell => cell.x));
    const minY = Math.min(...selectedCells.map(cell => cell.y));
    const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
    const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
    let mergedContent = "";
    selectedCells.forEach(cell => {
      mergedContent += cell.content + " "; // Concatenate the content of selected cells
      cell.showBorder = false;
      cell.width = 0;
      cell.height = 0;
      cell.content = ""; // Clear the content of the cell after merging
    });

    
    const startCell = getCellByCoords(minX, minY);
    if (startCell) {
      startCell.width = maxX - minX;
      startCell.height = maxY - minY;
      startCell.showBorder = true;
      startCell.content = mergedContent.trim(); // Update the content of the start cell

      updateCellSize(minX, minY,startCell.width, startCell.height);
    }

    
  }



  redraw();

  isIntoMenuSelection=0;//进入菜单选择状态
  } else if (y > 60 && y < 80) {
    console.log('取消 clicked');
    isIntoMenuSelection=0;//进入菜单选择状态
  }

  $(menuCanvas).hide();
});

// Initial hide of the menu canvas
	hideMenu();
  function drawCoordinates(x, y) {
  // Clear the canvas
  ctx1.clearRect(0, canvas1.height-12, canvas1.width, canvas1.height);
  
  // Optionally redraw other stuff here, e.g., a grid
  
  // Draw the coordinates
  ctx1.font = '14px Arial';
  ctx1.fillStyle = '#808080'; // Light blue color
  ctx1.fillText(x + '行 * ' +y+ '列 表格', 10, canvas1.height - 10);
}




          // Mousemove event to highlight squares
  $('#canvasPopup').mousemove(function(e) 
  {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    console.log('正在执行  表格 插入操作'); 
    drawGrid(); // Redraw the grid to clear previous highlights
    highlightSquares(x, y); // Highlight squares based on mouse position

   
    var selected = highlightSquares(x, y);
    // tableRows=selected.columns;
    // tableLines=selected.rows;
    drawCoordinates(selected.rows, selected.columns);

  });

    var canvas = $('#myCanvas')[0];
    var ctx = canvas.getContext('2d');
    var curOnBorder=0; //光标在边框上
    var curOnBorderAndButtonDown=0; //光标在边框上且左键按钮被按下  
    var leftButtonDown=0; //左键按钮被按下
    var onBottomLine=0;   //光标在表格底部边框上

    var isMoveTable=0;    //是否在移动表格 1=是 0=否
    var isOnMoveTable=0;  //是否在移动表格的边框上 1=是 0=否

      // 定义自定义光标样式
    var myCursor = "url('imgs/down_cursor.png'), auto";

    // Attach event handlers
  // $('#myCanvas').mousemove(handleMouseMove);
  // $('#myCanvas').mouseleave(handleMouseLeave);


  function renderPosition(x, y,showText) {
    // Clear a rectangle area for the coordinates to avoid overlap
    ctx.clearRect(20, 0, 550, 16); // Clear a small area at the top-left corner
    
    // Set font properties
    ctx.font = '14px Arial';
    ctx.fillStyle = '#808080';
    ctx.textAlign = 'left'; 
    //console.log('显示调整参数x:'+String(x)+' y:'+String(y));
    // Render the text
    ctx.fillText('X: ' + x + ', Y: '+y+' ('+showText+')' , 20, 8);
  }

    // Function to handle mouse movement within the canvas
  function handleMouseMove(event) {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    
    iconVisible = true; // Show the icon
    drawIcon(x, y);
  }

  // Function to hide the icon when the mouse leaves the canvas
  function handleMouseLeave() {
    iconVisible = false;
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  }


// 设置阴影的函数
function setShadow(shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY) {
    ctx.shadowColor = shadowColor;
    ctx.shadowBlur = shadowBlur;
    ctx.shadowOffsetX = shadowOffsetX;
    ctx.shadowOffsetY = shadowOffsetY;
  }

  // 绘制带阴影的矩形的函数
  function drawShadowedRect(x, y, width, height, shadowColor, shadowBlur, offsetX, offsetY, fillColor) {
    setShadow(shadowColor, shadowBlur, offsetX, offsetY);
    ctx.fillStyle = fillColor;
    ctx.fillRect(x, y, width, height);
    // 重置阴影，以便之后的绘制不会受到影响
    setShadow('rgba(0, 0, 0, 0)', 0, 0, 0);
  }

function updateForSellMerging()
  {
    	//调整后列新父亲单元格
      var parentRow = -1;
              var parentCol = -1;
              var parentRowSpan=0;
              var parentColSpan=0
            

              console.log("================================调整父单元格属性");
            jsonData.forEach(function(rowData, rowIndex) {
        					rowData.cells.forEach(function(cell, cellIndex) {
                    console.log("第:"+rowIndex+" 行 ，"+cellIndex+" 列 x:"+cell.x+" y:"+cell.y+
                    " width:"+cell.width+" height:"+cell.height+" showing:"+cell.showBorder+
                    " ParentRow:"+cell.parentRow+" parentCol:"+cell.parentCol+
                    " has rowspan:"+cell.rowspan+" has colspan:"+cell.colspan
                    );
                    if(cell.showBorder==false)
                    {
                      	parentRow = cell.parentRow;
						            parentCol = cell.parentCol;
                    		if(parentRow>=0&&parentCol>=0)//父亲单元格有跨度
												{
										  			var currentSelectCellOn=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex];//得到光标所在的单元格
										 			  var parentCell=jsonData[parentRow].cells[parentCol];	
								
										  			//获取父亲单元格的跨度
										  				parentRowSpan=jsonData[parentRow].cells[parentCol].rowspan;
										  				parentColSpan=jsonData[parentRow].cells[parentCol].colspan;	
                              
                              var parentHeight=0;
              								var parentWidth=0;
										  			//计算出跨度的高度
										  			for(let m=parentRow;m<=parentRow+parentRowSpan;m++)
														{
                              parentHeight+=jsonData[m].cells[parentCol].height;
														}
                         

										  			for(let n=parentCol;n<=parentCol+parentColSpan;n++)
														{
                              parentWidth+=jsonData[parentRow].cells[n].width;
														}
                            jsonData[parentRow].cells[parentCol].mWidth=parentWidth;
                            jsonData[parentRow].cells[parentCol].mHeight=parentHeight;
                            
														console.log("parent Width="+parentWidth+" parent Height="+parentHeight);
										  			console.log('isFatherCellUnderSelectedCell  currentSelectCellOn.y:'+currentSelectCellOn.y+' + currentSelectCellOn.height:'+currentSelectCellOn.height+ 
									  										' ='+String(currentSelectCellOn.y+currentSelectCellOn.height)+"  parentCell.y:"+parentCell.y+" + parentCell.mHeight: "+parentCell.mHeight+" = "+String(parentCell.y+parentCell.mHeight));
									
										 		
										

												}

                    }
       					 });
      					});
  }

  // 绘制带阴影的页面背景
  drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');



  //    jsonData = [
    
  //   {
  //     "cells": [
  //       {"content": "联办事项", "x":0, "y":0,        "width": 160, "height": 40, "borderSize": 1, "showBorder": true, "rowspan":3, "colspan":0,"parentRow":-1,"parentCol":-1,"mWidth":160,"mHeight":160,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "《出生医学证明》签发", "x":160, "y":0, "width": 160, "height": 40, "borderSize": 1, "showBorder": true, "rowspan":0, "colspan":3,"parentRow":-1,"parentCol":-1,"mWidth":540,"mHeight":40,"text-align":0,"hasCheckBox":true,"checkStatus":true},
  //       {"content": "", "x":160*2, "y":0, "width": 160, "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*3, "y":0, "width": 160, "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*4, "y":0, "width": 60,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false}
  //     ]
  //   },
  //   {
  //     "cells": [
  //       {"content": "", "x":0,     "y":40,   "width": 160, "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":0,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "国（境）内出生登记", "x":160*1, "y":40*1, "width": 160, "height": 40, "borderSize": 1, "showBorder": true, "rowspan":0, "colspan":3,"parentRow":-1,"parentCol":-1,"mWidth":540,"mHeight":40,"text-align":0,"hasCheckBox":true,"checkStatus":false},
  //       {"content": "", "x":160*2, "y":40*1, "width": 160,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":1,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*3, "y":40*1, "width": 160,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":1,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*4, "y":40*1, "width": 60,   "height":  40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":1,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false}
  //     ]
  //   },
	// {
	//   "cells": [
	//     {"content": "", "x":0,     "y":80,        "width": 160,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":0,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
	//     {"content": "城乡居民参保登记", "x":160*1, "y":40*2,  "width": 160, "height": 40, "borderSize": 1, "showBorder": true, "rowspan":0, "colspan":3,"parentRow":-1,"parentCol":-1,"mWidth":540,"mHeight":40,"text-align":0,"hasCheckBox":true,"checkStatus":true},
	//     {"content": "", "x":160*2, "y":40*2,"width": 160,   "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":2,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
	//     {"content": "", "x":160*3, "y":40*2,"width": 160,   "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":2,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
	//     {"content": "", "x":160*4, "y":40*2,"width": 60,    "height":  40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":2,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false}
	//   ]
	// },
  //   {
  //     "cells": [
  //       {"content": "", "x":0,     "y":120,  "width": 160, "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":0,"parentCol":0,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "社会保障卡申领 —— 社保卡办卡申请", "x":160*1, "y":40*3, "width": 160, "height": 40, "borderSize": 1, "showBorder": true, "rowspan":0, "colspan":3,"parentRow":-1,"parentCol":-1,"mWidth":540,"mHeight":40,"text-align":0,"hasCheckBox":true,"checkStatus":true},
  //       {"content": "", "x":160*2, "y":40*3, "width": 160,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":3,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*3, "y":40*3, "width": 160,  "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":3,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false},
  //       {"content": "", "x":160*4, "y":40*3, "width": 60,   "height": 40, "borderSize": 1, "showBorder": false, "rowspan":0, "colspan":0,"parentRow":3,"parentCol":1,"mWidth":0,"mHeight":0,"text-align":0,"hasCheckBox":false,"checkStatus":false}
  //     ]
  //   }
  // // ... 其他行，以此类推

  //   ];
	
	saveState()
    //统计更新表格总宽度
    for(var i=0; i<jsonData.length; i++)
    {
      for(var j=0; j<jsonData[i].cells.length; j++)
      {
        var cell = jsonData[i].cells[j];
        var content = cell.content;
        var width = cell.width;
        var height = cell.height;
        var borderSize = cell.borderSize;
        var showBorder = cell.showBorder;
        lastTableTotalWidth+=width;
      }
      break;
    }


    // 绑定删除最后一行按钮的点击事件
		$('#deleteLastRow').click(function() {
  	jsonData.pop(); // 删除最后一行
    saveState()
    console.log("剩余行数: " + jsonData.length); // 打印剩余的行数
    tableRows=jsonData.length;
    tableLines=jsonData.length;
 

    updateTotalHeight();// 重新计算表格总高度

  	redraw(); // 重新绘制表格
		});

// 绑定删除最后一列按钮的点击事件
$('#deleteLastColumn').click(function() {

  
  jsonData.forEach(row => {
    row.cells.pop(); // 每一行删除最后一个单元格
  });

    tableRows=jsonData[0].cells.length;
    saveState()

    console.log("剩余列数: " + (jsonData[0].cells.length)); // 假设所有行的列数相同，打印剩余的列数
    updateTotalWidth();// 重新计算表格总宽度
    updateTotalHeight();// 重新计算表格总高度

     redraw(); // 重新绘制表格
});



    function drawTableOnCanvas(rows, cols) {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    // Calculate cell width and height
    var cellWidth = canvas.width / cols;
    var cellHeight = canvas.height / rows;

    // Clear the canvas before drawing
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the table
    for (var i = 0; i < rows; i++) {
      for (var j = 0; j < cols; j++) {
        var x = j * cellWidth;
        var y = i * cellHeight;
        
        // Draw cell border
        ctx.strokeRect(x, y, cellWidth, cellHeight);

        // Fill cell with text
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        var text = 'Cell ' + (i+1) + ',' + (j+1);
        ctx.fillText(text, x + cellWidth / 2, y + cellHeight / 2);
      }
    }
  }



    function drawTable(data) {
      var cellStartX = tableOffsetX;
      var cellStartY = tableOffsetY;
      var alignTypes = ['left', 'center', 'right'];
      // 遍历表格数据，行数据
      // var rows = data.length;
      // var cols = data[0].cells.length;
      jsonData.forEach(function(rowData, rowIndex) {
        rowData.cells.forEach(function(cell, cellIndex) {
          var x = cellStartX + cell.x;
          var y = cellStartY + cell.y;        
    
          if(cell.showBorder==true)
          {
            ctx.beginPath();

            if(cell.colspan>=1||cell.rowspan>=1)
            {
              ctx.rect(x, y, cell.mWidth, cell.mHeight);
            }
            else
            {
              ctx.rect(x, y, cell.width, cell.height);
            }
           
            ctx.fillStyle = cell.selected ? 'lightblue' : 'white';
              // 设置字体样式
        			ctx.font = '16px Microsoft YaHei';
       			

            ctx.fill();
            if (cell.showBorder) {
              ctx.lineWidth = cell.borderSize;
              ctx.textBaseline = 'middle';
              ctx.strokeStyle = 'black';
              ctx.stroke();
            }
            ctx.fillStyle = 'black';
            ctx.textBaseline = 'middle';
            ctx.textAlign = 'left';




            if(cell.colspan>=1||cell.rowspan>=1)
            {
                var checkBoxX=0;
                var checkBoxY=0;
              // 绘制复选框
                      if (cell.hasCheckBox) {
                        var checkBoxImg = cell.checkStatus ? checkedBoxImage : checkBoxImage;
                        console.log("Check status:"+cell.checkStatus+checkBoxImg);
                        // 请根据你的图片实际大小调整这里的偏移和位置
                        checkBoxX = x + 5; // 举例，复选框距单元格左边界10像素
                        checkBoxY = y + (cell.mHeight - checkBoxImg.height) / 2; // 复选框垂直居中
                        if(cell.checkStatus===true)
                        ctx.drawImage(checkedBoxImage, checkBoxX, checkBoxY);
                      else
                      ctx.drawImage(checkBoxImage, checkBoxX, checkBoxY);
                      }
                      else
                      {
                        console.log("has no checkCtrl :"+cell.checkStatus+checkBoxImg);
                      }

                      var textX = x + (cell.hasCheckBox ? 45 : 10); // 如果有复选框，则增加偏移
        			        var textY = y ;

                      var myTextAlign=0;
                      var verticalAlign=0;
                      if(cell!=null)
                      {
                        myTextAlign=cell.textAlign;
                        verticalAlign=cell.verticalAlign;
                        indent = cell.indent;
                        bold=cell.bold;
                        italic=cell.italic;
                        underline=cell.underline;
                        underlineColor=cell.underlineColor;
                        backgroundColor=cell.backgroundColor;
                        underlineStyle=cell.underlineStyle;
                        strikethrough=cell.strikethrough;
                        underlineColor=cell.underlineColor;
                        color=cell.color;
                        fontSize=cell.fontSize;
                        font=cell.font;
                      }

                      console.log("A3 font color:"+fontSize);
                      
                                           

                      ///ctx.fillText(cell.content, textX, textY);
                      drawTextInRect(ctx, cell.content, textX, textY+5, cell.mWidth-checkBoxX-10, cell.mHeight, myTextAlign, displayMode, verticalAlign, font, cell.fontSize, indent, color, underline, strikethrough, italic,underlineColor,underlineStyle,backgroundColor,currentLineSpacing,bold);

                      //ctx.fillText(cell.content, cell.x+cellStartX + cell.mWidth / 2+checkBoxX, cell.y+cellStartY + cell.mHeight / 2);
            }

          else
          {
           			if (cell.hasCheckBox) {
                        var checkBoxImg = cell.checkStatus ? checkedBoxImage : checkBoxImage;
                        console.log("Check status:"+cell.checkStatus+checkBoxImg);
                        // 请根据你的图片实际大小调整这里的偏移和位置
                        var checkBoxX = x + 5; // 举例，复选框距单元格左边界10像素
                        var checkBoxY = y + (cell.height - checkBoxImg.height) / 2; // 复选框垂直居中
                        if(cell.checkStatus===true)
                        ctx.drawImage(checkedBoxImage, checkBoxX, checkBoxY);
                        else
                        ctx.drawImage(checkBoxImage, checkBoxX, checkBoxY);
                      }
                      else
                      {
                        console.log("2 has no checkCtrl !");
                      }
                      var textX = x + (cell.hasCheckBox ? 45 : 10); // 如果有复选框，则增加偏移
        			  var textY = y ;

                      var myTextAlign=0;
                      var verticalAlign=0;
                      if(cell!=null)
                      {
                        myTextAlign=cell.textAlign;
                        verticalAlign=cell.verticalAlign;
                        indent = cell.indent;
                        bold=cell.bold;
                        italic=cell.italic;
                        underline=cell.underline;
                        underlineColor=cell.underlineColor;
                        backgroundColor=cell.backgroundColor;
                        underlineStyle=cell.underlineStyle;
                        strikethrough=cell.strikethrough;
                        underlineColor=cell.underlineColor;
                        color=cell.color;
                        fontSize=cell.fontSize;
                        font=cell.font;
                      }
                      //ctx.textAlign = alignTypes[myTextAlign] || 'left'; // 设置文本对齐方式

            console.log("A1 befor drawTextInRect textY:"+textY+ "  cellStartY:"+cellStartY+" verticalAlign:"+verticalAlign+"  textAlign:"+myTextAlign);
            console.log("A2 font color:"+color);
            //ctx.fillText(cell.content, textX, textY);
                       // 初始绘制文本
            drawTextInRect(ctx, cell.content, textX,  textY, cell.width-10, cell.height, myTextAlign, displayMode, verticalAlign, font, cell.fontSize, indent, color, underline, strikethrough, italic,underlineColor,underlineStyle,backgroundColor,currentLineSpacing,bold);

             //ctx.fillText(cell.content, cell.x+cellStartX + cell.width / 2+checkBoxX, cell.y+cellStartY + cell.height / 2);
             // 初始绘制文本
          
          }
         

          }
          
          
        });
       

      });
       // cellStartY += cell.height;

        /////////////////////////////////////

        // ctx.clearRect(0, 0, canvas.width, canvas.height);
        // for (let i = 0; i < rows; i++) {
        //   for (let j = 0; j < cols; j++) {
        //     const cell = table[i][j];
        //     ctx.beginPath();
        //     ctx.rect(cell.x, cell.y, cell.width, cell.height);
        //     ctx.fillStyle = cell.selected ? 'lightblue' : 'white';
        //     ctx.fill();
        //     if (cell.showBorder) {
        //       ctx.lineWidth = cell.borderSize;
        //       ctx.strokeStyle = 'black';
        //       ctx.stroke();
        //     }
        //     ctx.fillStyle = 'black';
        //     ctx.textBaseline = 'middle';
        //     ctx.textAlign = 'center';
        //     ctx.fillText(cell.content, cell.x + cell.width / 2, cell.y + cell.height / 2);
        //   }
        // }

        /////////////////////////////////////
      
    }



   // redraw();

function drawTableFromJson(jsonData) { //绘制表格
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);


  //遍历每一行
  jsonData.forEach(function(rowData, rowIndex) {
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {      
        ctx.strokeRect(cell.x, cell.y, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";  
      ctx.fillText(cell.content, cell.x + cell.width / 2, cell.y + cell.height / 2);
    });
    //currentY += rowData.cells[0].height;
  });
}

// 在变化之前查找表格行列数
function getCRFormCell(x, y,description) 
{
 
     console.log(description+ "x: " + x + ", y: " + y);
     //遍历行
     for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
       var row = jsonData[rowIndex].cells;
       //遍历列
       for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
         var cell =jsonData[rowIndex].cells[cellIndex];

        // console.log("遍历 第" + String(rowIndex) + "行第" + String(cellIndex) + "列; X:"+ String(cell.x)+ " Y:"+ String(cell.y)+" w:"+cell.width+" h:"+String(cell.height));

         //判断点击位置是否在单元格内
         if (x >= cell.x && x <= (cell.x + cell.width) &&
             y >= cell.y && y <= (cell.y + cell.height)) {
            console.log("description:"+description + String(rowIndex) + "行第" + String(cellIndex) + "列; X:"+ String(x)+ " Y:"+ String(y));
           return {row:rowIndex, col:cellIndex};
          }//返回单元格坐标
         }
         
       }
       return null;
}
  


// Get cell by coordinates
function getCellByCoords(x, y) {
 
  let offset=0;
      //遍历行
      for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
        var row = jsonData[rowIndex].cells;
        //遍历列
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
          var cell = row[cellIndex];
          //判断点击位置是否在单元格内
          if (x >= cell.x+offset && x <= (cell.x + cell.width-offset) &&
              y >= cell.y+offset && y <= (cell.y + cell.height-offset)) {
            return cell;//返回单元格坐标
          }
          
        }
       
      }
    return null;
  }

  function updateCellSize(row,col,x,y,w,h)
  {    
    console.log("=====+更新行:"+String(row)+" 列："+String(col)+" 坐标："+String(x)+","+String(y)+" 宽："+String(w)+" 高："+String(h));
        jsonData[row].cells[col].x=x;
        jsonData[row].cells[col].y=y;
        jsonData[row].cells[col].mWidth=w;
        jsonData[row].cells[col].mHeight=h;
        jsonData[row].cells[col].showBorder=true;
            

  }
    function getCellFromCoords(x, y) {
      var startX = 0;
      var startY = 0;
      //遍历行
      for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
        var row = jsonData[rowIndex].cells;
        //遍历列
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
          var cell = row[cellIndex];
          //判断点击位置是否在单元格内
          if (x >= startX && x <= startX + cell.width &&
              y >= startY && y <= startY + cell.height) {
            return {row: rowIndex, col: cellIndex};//返回单元格坐标
          }
          startX += cell.width;
        }
        startX = 0;
        startY += row[0].height;
      }

      return null;
    }





    function getCellStartX(rowIndex, colIndex)
    {
      var x=0;
      var y=0;
      //遍历行，从0到colIndex
      for (var j = 0; j <colIndex ; j++) {
          x+=jsonData[rowIndex].cells[j].width
        }
      for (var i = 0; i < rowIndex; i++) {
       
          y+=jsonData[i].cells[colIndex].height;
       
      }
      x=x+tableOffsetX;
      y=y+tableOffsetY;
      return {x:x,y:y};
    }


    function redraw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
      drawTable(jsonData);
     
    }

    // function redrawBySelect(startX,startY,mouseX,mouseY) {

    //   ctx.clearRect(0, 0, canvas.width, canvas.height);
    //   drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
    //   drawTable(jsonData);
    //   currentSelection.forEach(function(cell) {
       
    //     var cellStartX = cell.col * jsonData[0].cells[cell.col].width;
    //     var cellStartY = cell.row * jsonData[cell.row].cells[0].height;
    //     var cellData = jsonData[cell.row].cells[cell.col];
    //     drawCell(ctx, cellData, cellStartX, cellStartY, true);
    //   });
    //    // 绘制页面边框
    //   ctx.strokeStyle = '#cccccc';
    //   ctx.lineWidth = 1;
    //   ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

    //   ctx.beginPath();
    //   ctx.setLineDash([5, 3]); // 保证虚线样式
    //   ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
    //   ctx.stroke();
    //   ctx.setLineDash([]); // 保证

    // }



    function updateTotalWidth()
    {
      tableTotalWidth=0;
      
          for(var m=0;m<jsonData[0].cells.length;m++)
            {
              tableTotalWidth+=jsonData[0].cells[m].width;
            }
    }

    function updateTotalHeight()
    {
           tableTotalHeight=0; //重新计算表格总高
            for(var n=0;n<jsonData.length;n++)
            {
              tableTotalHeight+=jsonData[n].cells[0].height;
            }
    }

    $('#canvasPopup').mousedown(function(e) {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    var selected = highlightSquares(x, y);
    
    //alert('Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns);


    console.log('正在执行  表格 插入操作 Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns); 

   
    var jsonData = generateJsonData(selected.rows, selected.columns);
  	//drawTableFromJson(jsonData);
    tableRows=selected.columns;
    tableLines=selected.rows;
    tableColumns=selected.columns;

    updateTotalWidth();// 重新计算表格总宽度
    updateTotalHeight();// 重新计算表格总高度
    redraw();
    // 绘制第二个图层的表格
    // drawTableOnLayer2(selected.rows, selected.columns);
    // 调用函数绘制表格
    //drawTableOnLayer2WithMargins(selected.rows, selected.columns, marginTop, marginBottom, marginLeft, marginRight);
           // 绘制页面边框
           var ctx = canvas1.getContext('2d');
  				ctx.strokeStyle = '#cccccc';
  				ctx.lineWidth = 1;
  				ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

    $('#canvasPopup').hide(); // 隐藏第一个 canvas 层




  });


      drawTable(jsonData);

       // 绘制页面边框
  ctx.strokeStyle = '#cccccc';
  ctx.lineWidth = 1;
  ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

   
      var currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
      var currentSelectedCellIndex=0;    //当前选中的单元格所在列索引
  
      var tableColumns=0;                //表格列数
      var tableLines=0;									 //表格行数
    
      var curOnTheRightBoarder=0;         //光标在右侧边框上
      var curOnTheBottomBoarder=0;        //光标在底部边框上ing
     
      var isSelectRegionDrawing = false;    //是否开始选择操作


 
    //表格区域提示图标
  var icon = new Image();
  var iconLoaded = false; // Flag to check if the icon has loaded
  var iconVisible = false; // Flag to toggle icon visibility

  // Set your PNG icon's URL
  icon.src = 'imgs/move_icon.png'; // Replace 'your-icon.png' with the path to your icon
  icon.onload = function() {
  iconLoaded = true;
   
  };

      canvas.addEventListener('mousemove', function(e) {

      var canvasOffset = $('#myCanvas').offset();

      var canvas = $('#myCanvas');
      var context = canvas.get(0).getContext('2d');
      var cursorX = event.pageX;
      var cursorY = event.pageY;

   
     
      var currentCell=null;
      var keysArray = Object.keys(jsonData);      
	    tableLines= keysArray.length;       
      var startX = canvasOffset.left+tableOffsetX; //画布左边，画布的X起始点
      var startY = canvasOffset.top+tableOffsetY;  //画布顶边，画布的Y起始点

      var found=0;
      var selectCellLeft=0;
      var selectCellTop=0;
      var selectCellRight=0;
      var selectCellBottom=0;

      var offset = 6; 				// 光标与边线的偏移量
      var curOffsetX=offset;  
      var curOffsetY=offset;
      var curOffsetMy=offset;
  
      var inRightPosition=0;

   
      if( isIntoMenuSelection==1)//进入菜单选择状态
      {
        return;
      }
      
        for(var n=0;n<tableLines;n++)
        {
          tableTotalHeight+=jsonData[n].cells[0].height;
        }


        updateTotalWidth();// 初始化表格总长度
        updateTotalHeight();//初始化表格总高度
    


      if(isMoveTable==1)
      {
        console.log('正在执行  表格 移动操作'); 
        tableOffsetX = cursorX-canvasOffset.left;
        tableOffsetY = cursorY-canvasOffset.top;
        redraw();
        showText="正在移动表格:"+tableOffsetX+","+tableOffsetY;
        renderPosition(cursorX,cursorY,showText);
        return;
      }
      if(cursorX>startX-offset*2&&cursorX<startX&& cursorY>startY-offset*2&&cursorY<startY) //
       {
           isOnMoveTable=1;
           inRightPosition=1;
           whereCurIs=4;
           console.log('监测到    表格 移动区域：');
           var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
           document.body.style.cursor = myCursor;
       }
       else
       {

        isMoveTable=0;
        isOnMoveTable=0;
       }

      var showText="";
      if( curOnBorder==1&&curOnBorderAndButtonDown==1)
      {

        //currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
        //currentSelectedCellIndex=0;    //当前选中的单元格所在列索引     

        var direct='调整列宽';
        if(whereCurIs==1)
        direct='调整行高';

        //console.log('正在调整中 '+direct+' 操作方向:'+whereCurIs+' 列数：'+tableColumns+' 光标坐标：(' + cursorX + ', ' + cursorY + ' curOnBorder:'+curOnBorder+', curOnBorderAndButtonDown:'+curOnBorderAndButtonDown+' 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex+')');


        //处理光标在表格最右边的情况
        if(curOnTheRightBoarder==1)
        {
            var totalOffsetX=0;
            console.log('正在调整中 宽度---------- ');
            for(var j=0;j<currentSelectedCellIndex;j++)
            {
              
              console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
                totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
        
            }
            //更新当前列单元格的宽
            for(var i=0;i<tableLines;i++)
            {
              var tempWidth=cursorX-totalOffsetX-startX;//最后一个单元格的宽，需要减去其它单元格的总宽度
              console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格宽度："+String(tempWidth));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(currentSelectedCellIndex>=0) //
              {
                if(tempWidth>=15)
                jsonData[i].cells[currentSelectedCellIndex].width=tempWidth;
              }
              
          
            }

            showText="最右边单元格宽："+String(tempWidth);
            //更新表格总宽度
            updateTotalWidth(); //重新计算表格总宽度
            updateTotalHeight();//重新计算表格总高度
            lastTableTotalWidth=tableTotalWidth;//记录上一次的表格总宽度
            updateForSellMerging();
            redraw();
            renderPosition(cursorX,cursorY,showText);
            return ;
        }

        if(curOnTheBottomBoarder==1)//处理光标在表格最下边的情况
        {

          var totalOffsetY=0;
            for(var j=0;j<tableLines-1;j++)
            {
              
              console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新列:'+j+" 列号：0 单元格高："+String(jsonData[j].cells[0].height));
                totalOffsetY+=jsonData[j].cells[0].height;//最一行之前N行高之和
        
            }

            var currentRowHeight=cursorY-startY-totalOffsetY; //最后一行的高度正在变化，所以要减去前面的行高
            showText="最下边单元格高："+String(currentRowHeight);
            //更新当最后一行单元格的高
            for(var i=0;i<tableColumns;i++)
            {
             
              console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新行:'+currentSelectedCellIndex+" 上单元格宽度："+String(currentRowHeight));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(tableLines>=0)
              {
                if(curOnTheBottomBoarder==1)
                {
                  if(currentRowHeight>=15)
                  jsonData[tableLines-1].cells[i].height=currentRowHeight; //对最后一行进行更新
                }
               
              }
              
          
            }

            tableTotalHeight=0
            updateTotalHeight(); //重新计算表格总高
            updateForSellMerging();//

            redraw();
            renderPosition(cursorX,cursorY,showText);
            return ;

        }

		function getTotalOffsetYbefor() {
			var offsetY=0;
			for(var r=0;r<currentSelectedCellRowIndex;r++)
			{
			  if(r<currentSelectedCellRowIndex-1)
			  {
			    offsetY+=jsonData[r].cells[0].height;
			  }
			          
			}
			
			return offsetY;
		}

    function getTotalOffsetOfY()
    {
      var offsetY=0;
      			for(var j=0;j<currentSelectedCellRowIndex;j++)
            {
              if(j<currentSelectedCellRowIndex-1)
              {
                offsetY+=jsonData[j].cells[0].height;
              }
                      
            }
            return offsetY;
    }
		/////////////////////////////////////////////////////////////////////////////////////////////
		//调整行高:同一行所有单元格的行高都改变，bottom的Y值等于cursorY
		////////////////////////////////////////////////////////////////////////////////////////////
    if(whereCurIs==1)//调整行高:同一行所有单元格的行高都改变，bottom的Y值等于cursorY
        {
			      //计算当前单元格上面所有单元格的高度。tableLines
            var totalOffsetY=getTotalOffsetOfY();
         
            //更新当前行单元格的高，， //startY画布顶边，画布的Y起始点//totalOffsetY当前行上面所有单元格的高度
         
            var cellsHeightOfCurrentRowBefore=cursorY-startY-totalOffsetY;//当前行上面所有单元格的高度之和
            var offsetCurrentY=0;//下一行的Y启始坐标
            var upCellHeightOffset=totalOffsetY+cellsHeightOfCurrentRowBefore;
            for(var i=currentSelectedCellRowIndex;i<tableLines;i++)
            {
             
              console.log('------------调整单元格大小，当前更新行:'+currentSelectedCellRowIndex+" 上面所有单元格高度和："+String(cellsHeightOfCurrentRowBefore));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              
			        if(currentSelectedCellRowIndex-1>=0)
              {   
                for(var j=0;j<tableColumns;j++)
              	{
                	if(cellsHeightOfCurrentRowBefore>=15)
                  {
                  if(currentSelectedCellRowIndex-1>=0) //被编辑的行的高度会变，大于顶行
                  {

                    console.log('调整单元格第几行 i：'+String(i)+' 第j：'+String(j) +' 选中单元格在表的行号 currentSelectedCellRowIndex:'+String(currentSelectedCellRowIndex)+' 两者相同表示是选中行');
                    if(i==currentSelectedCellRowIndex) //调整当前行的单元格高度
                    {
                      jsonData[i-1].cells[j].height=cellsHeightOfCurrentRowBefore;
                      jsonData[i].cells[j].y=upCellHeightOffset;
                      console.log('确认是当前表格选中行+++++++++++++++++++++++++++++++');
                    }
                    else
                    {
                      jsonData[i].cells[j].y= upCellHeightOffset;
                    }
                   
                   
                    
                    
                  }
                  else
                  {   //jsonData[i].cells[j].y+=totalOffsetY+cellsHeightOfCurrentRowBefore;
											//jsonData[i].cells[j].y=upCellHeight;
                      //offsetCurrentY=jsonData[i].cells[j].height;
                  }
                  

                  
                	}
                  
              	}	
                upCellHeightOffset+= jsonData[i].cells[currentSelectedCellIndex].height;
              }          
             
			 
            }

            
            if(cellsHeightOfCurrentRowBefore>=15)
            {
              showText="当前调整单元格高："+String(cellsHeightOfCurrentRowBefore);
            }
            else
            {
              showText="当前调整单元格高：16";
            }
						//调整后列新父亲单元格
            updateForSellMerging();
            //开始调整有合并的单元格
            
            
        }
		



		
		if(whereCurIs==2)//调整列单元格宽,左侧调整列宽，右则也相反方向调整列宽
		{
			//计算当前单元格上面所有单元格的宽度。tableLines
			var totalOffsetX=0; //调整列之前的单元格总宽
			var restOffsetX=0;  //调整列之后的单元格总宽

      var hasAnySelectCellWith=0;    //记录当前表格中，是否有当前光标下，是否有选中的单元格，如果有仅处理相关单元格，否则要处理整个表格
      var hasAnyMergeCellWith=0;     //记录当前表格中，是否有当前光标下，是否有合并的单元格，如果有要比较当前合并的单元格与当前所选的单元格是不是行号一致。如果不一致，不能调整列宽操作。
      var selectCellLineString="";   //单元格选择的行集
      var selectMergeCellString="";  //相关和合并单元格的行集
      var hadMergeCellString=0;      //标识完成合并单元格查找，用于避免重复查找
      var selectedCellOnMinRow=1000; //确定有效选择单元格最顶行行号。
      var selectedCeloOnMaxRow=0;    //确定有效选择单元格最底部行号。
      var whereIsMergecel=0;         //0表示没有发现有合并单元格在当前光标下，1表示有合并单元格在当前光标下（同行），2表示左则有
      var mergeCellOnMinRow=1000;    //合并单元格最顶行号
      var mergeCellOnMaxRow=0;       //合并单元格最底部行号
       
      var hadShereLine=0;            //判断选择区 和  合并单元格有e交集


      //为了判断所在的表格中，是否有当前光标下，是否有选中的单元格，如果有仅处理相关单元格，否则要处理整个表格
        for(var i=0;i<tableLines;i++)  //从第一行开始查找
        {
            //查找当光标位置，左是否有选的单元格
            if(jsonData[i].cells[currentSelectedCellIndex-1].selected==1||jsonData[i].cells[currentSelectedCellIndex].selected==1)
            {

              //冒泡最大最小行号
              if(i<selectedCellOnMinRow)
              selectedCellOnMinRow=i;
              if(i>selectedCeloOnMaxRow)
              selectedCeloOnMaxRow=i;


              hasAnySelectCellWith++;
              console.log("A4 找到选中的单元格，line:"+i+" col:"+currentSelectedCellIndex);
             
              if(selectCellLineString==="")
                selectCellLineString=i;
              else
                selectCellLineString= selectCellLineString+","+i;
            }

            if(jsonData[i].cells[currentSelectedCellIndex-1].parentRow>=0&&jsonData[i].cells[currentSelectedCellIndex].selected==1) //左则有合并单元格,行数大于0,并与选中行同行
            {
              var parentCellRowIndex=jsonData[i].cells[currentSelectedCellIndex-1].parentRow;
              var parentCellColIndex=jsonData[i].cells[currentSelectedCellIndex-1].parentCol;
              var parentCell=  jsonData[parentCellRowIndex].cells[parentCellColIndex];

              console.log("A4 有合并的单元格:"+i+" col:"+currentSelectedCellIndex);

                  if(hadMergeCellString==0)
                  {
                      for(var m=parentCellRowIndex;m<=parentCell.rowspan;m++)
                      {
                        if(selectMergeCellString==="")
                        {
                          selectMergeCellString=m;
                        }
                        else
                        {
                          selectMergeCellString=selectMergeCellString+","+m;
                        }

                        console.log("A4 找到被合并相邻单元格行集，line:"+i+" col:"+currentSelectedCellIndex+" 集合有："+selectMergeCellString);
                        hasAnyMergeCellWith++;
                        whereIsMergecel=1;

                        if(m< mergeCellOnMinRow)
                        mergeCellOnMinRow=m;    //合并单元格最顶行号

                        if(m>mergeCellOnMaxRow)
                        mergeCellOnMaxRow=m;       //合并单元格最底部行号


                      }
                      hadMergeCellString=1;

                  }
               
            }

            //另一种可能：合并单元格与当前选择的单元格同行，且当前选择的单元格是合并单元格的子单元格
            if(hadMergeCellString==0)
            {
                console.log("A4 if(rowspan>0){"+jsonData[i].cells[currentSelectedCellIndex-1].rowspan+"}&& selected={"+jsonData[i].cells[currentSelectedCellIndex].selected+"}");
                if(jsonData[i].cells[currentSelectedCellIndex-1].rowspan>0&&jsonData[i].cells[currentSelectedCellIndex].selected==1) //左则有合并单元格,行数大于0,并与选中行同行
                {

                 
                  var parentCell=  jsonData[i].cells[currentSelectedCellIndex-1];//定位到合并单元格的主单元格

                  console.log("A4 有合并的单元格:"+i+" col:"+(currentSelectedCellIndex-1)+" 跨行数： parentCell.rowspan="+parentCell.rowspan);

                 
                      for(var m=i;m<=parentCell.rowspan;m++)
                      {
                        if(selectMergeCellString==="")
                        {
                          selectMergeCellString=m;
                        }
                        else
                        {
                          selectMergeCellString=selectMergeCellString+","+m;
                        }

                        hasAnyMergeCellWith++;
                        if(m<= mergeCellOnMinRow)
                        mergeCellOnMinRow=m;    //合并单元格最顶行号

                        if(m>=mergeCellOnMaxRow)
                        mergeCellOnMaxRow=m;       //合并单元格最底部行号

                        console.log("A4 找到被合并相邻单元格行集，line:"+i+" col:"+currentSelectedCellIndex+" 集合有："+selectMergeCellString);

                      }
                      hadMergeCellString=1;
                      whereIsMergecel=2;

                 

                  console.log("A4 找到被合并相邻同行单元格行集，line:"+i+" col:"+currentSelectedCellIndex);

                  
                }

            }
            

          
      
        
      }

      // var selectedCellOnMinRow=1000; //确定有效选择单元格最顶行行号。
      // var selectedCeloOnMaxRow=0;    //确定有效选择单元格最底部行号。
      console.log("A4 有效行号顶行："+selectedCellOnMinRow+" 底部行号："+selectedCeloOnMaxRow+ " 1合并单元在左侧 2在同行："+ whereIsMergecel);
      console.log("A4 合并行号顶行："+mergeCellOnMinRow+" 底部行号："+mergeCellOnMaxRow);


    //当mergeCells区域在上边，selectedCells在下边。求是否有交集：
    var hasShearLineA=0;
    //M代表mergeCells, S代表 selectedCells;

    //判断mergeCells与selectedCells的方位关系(M上S下)
    if(selectedCellOnMinRow>mergeCellOnMinRow)
    {
      
      if(selectedCellOnMinRow-mergeCellOnMaxRow>0)
      hasShearLineA=0;
      else
      hasShearLineA=1;


    }
    console.log("A4 (M上S下) 区域有交集:"+hasShearLineA);


    //当selectedCells 区域在上边，mergeCells在下边。求是否有交集：
    var hasShareLineB=0;
       //判断mergeCells与selectedCells的方位关系(S上M下)
    if(mergeCellOnMinRow >selectedCellOnMinRow)
    {
      

      if(mergeCellOnMinRow-selectedCeloOnMaxRow>0)
      hasShareLineB=0;
      else
      hasShareLineB=1;
    }
    console.log("A4 (S上M下) 区域有交集:"+hasShareLineB);

  

    if(hasShearLineA==1||hasShareLineB==1)
     hadShereLine=1;
     console.log("A4 selectedCells在mergeCells区域有交集:"+hadShereLine);
     //selectedCells在mergeCells区域区间
    if(mergeCellOnMinRow<selectedCellOnMinRow&&mergeCellOnMinRow<selectedCeloOnMaxRow&&mergeCellOnMaxRow>selectedCellOnMinRow&&mergeCellOnMaxRow>selectedCellOnMinRow)
    hadShereLine=1;

    console.log("A4 A selectedCells在mergeCells区域有交集:"+hadShereLine);
     if((selectedCellOnMinRow-selectedCeloOnMaxRow>0)&&(selectedCeloOnMaxRow-selectedCeloOnMaxRow>0))
     {
      hadShereLine=0;
     }

     console.log("A4 B selectedCells在mergeCells区域有交集:"+hadShereLine);
      console.log("A4 找到选中的单元格数，hadShereLine:"+hadShereLine+" hasAnySelectCellWith:"+hasAnySelectCellWith+"  hasAnyMergeCellWith:"+hasAnyMergeCellWith+  " 选择的行集："+selectCellLineString+"  合并格行集："+selectMergeCellString+" 表格总行数："+tableLines);

      if(whereIsMergecel==2)//同行有合并的单元，判断
      {
        if(selectCellLineString!==selectMergeCellString) //断定被选中的单元格与合并单元格不是在相同的行号上，则不能调整列宽
        {
          return;
        }

      }
      //当选择表格有单元格在调整区域，同时周边有被合并单元格的集合,两个区域有交集
      if(hasAnySelectCellWith>0&&hasAnyMergeCellWith>0&&hadShereLine==1)
      {
        if(selectCellLineString!==selectMergeCellString) //断定被选中的单元格与合并单元格不是在相同的行号上，则不能调整列宽
        {
          return;
        }
        
      }
      else
      {
        if(hasAnyMergeCellWith==0)
        {
          console.log("A4 在周边没有找到合并单元格");
        }
      }
      


      //当前一个单元格宽度变化时，后一个单元格的宽度变化，X坐标也做相应的变化
      //X坐标变化量=当前一个单元格宽度+totalOffsetX
     
      //记信当前前后单元格变化前的值，用于后面辅助计算，单元格移动方向 
      var currentLeftCellWidth; //当前单元格左边单元格的宽度
      var currentRightCellWidth;//当前单元格右边单元格的宽度
      var moveToLeft=1;//0向左移动，1向右移动
      //记录当前单元格左边和右边单元格的宽度
      currentLeftCellWidth=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex-1].width; //左边表格
      currentRightCellWidth=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex].width; //右边表格

			for(var j=0;j<currentSelectedCellIndex-1;j++)
			{
				
        //console.log('调整单元格大小==》，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
        if(j<tableColumns)
				totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
	
			} 

      for(var j=currentSelectedCellIndex+1;j<tableColumns;j++) 
      {
       // console.log('j:'+String(j)+'行先:'+String(currentSelectedCellRowIndex+1));
        if(currentSelectedCellRowIndex+1<=tableLines)
          restOffsetX+=jsonData[0].cells[j].width;//选中行下后N列的宽
          
        
       
      }
      
        var tempWidth=cursorX-startX-totalOffsetX; //计算出当前光标左列的宽度，
        var afterCellWidth=jsonData[0].cells[currentSelectedCellIndex].width;//光标右则的单元格更新后的高，计算值；
       

        //如果光标在最后一列，最后一是列的宽度小于15后，向左拉时，表格最右边保持不变
        if(afterCellWidth>=15)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-cursorX+startX;
          
        }

     
        
        if(currentSelectedCellIndex>=0&&currentSelectedCellIndex<tableColumns)
        {
            
						//console.log('选中列：'+currentSelectedCellIndex+'当前表格总宽度：'+String(tableTotalWidth)+' totalOffsetX：'+String(totalOffsetX+tempWidth)+' restWidth:'+String(restOffsetX)+' 上一次表格总宽度:'+String(lastTableTotalWidth)+'calculate total:'+String(currentLeftCellWidth+currentRightCellWidth+restOffsetX+totalOffsetX));

            //如果宽度变小，则需要调整右边表格的宽度
            var subWidth= g_selectedCellWidth_L-tempWidth;//老的宽度-变化后的宽度

            if(tempWidth>0)//左单元格比之前变小，右则的单元格宽度需要变宽
            {
              if((totalOffsetX+tempWidth+restOffsetX)<lastTableTotalWidth-15)
              {
                if((jsonData[0].cells[currentSelectedCellIndex].width-subWidth)>=15)//后面的单元格宽度足够
              	{
                 afterCellWidth=currentRightCellWidth+subWidth;
                 
              	}  		 
              }
              else
              {
                return;
              }
                       
             
            }
            else//变窄
            {
              afterCellWidth=currentRightCellWidth-subWidth;
            }

        }
         

      //更新当前列单元格的宽
        if(lastTableTotalWidth-totalOffsetX+tempWidth-restOffsetX<0)//判读光标后一列单元格小于16
        {
          
          	
              afterCellWidth=16;
              tempWidth=lastTableTotalWidth-totalOffsetX-afterCellWidth-restOffsetX;        
           
          // console.log('越过总长度:'+String(totalOffsetX+tempWidth+afterCellWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
          // curOnBorder=0;
          //  return;
        }
        //当最新表宽大于旧表宽时，需要调整列宽
       
        if((totalOffsetX+afterCellWidth+restOffsetX+tempWidth)<lastTableTotalWidth)
        {
          if(tempWidth<=15)
          {
             tempWidth=15;
          }
         
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
          console.log('总长度受影响越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
        
        }

        //修正总表宽度大于最新表宽度时，需要调整列宽
        if((totalOffsetX+tempWidth+afterCellWidth+restOffsetX)>lastTableTotalWidth)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
         
          //console.log('总长度受影响大越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
      
        }
      
        showText="左单元格宽:"+String(tempWidth)+" 右单元格宽:"+String(afterCellWidth);
     
        var tempCounterTotalOffsetX=0; //调整列之前的单元格总宽
        for( var j=0;j<tableColumns;j++)
        {
          tempCounterTotalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;
          
        }
        // if(tempCounterTotalOffsetX>lastTableTotalWidth)
        // {
        //   console.log('===========调整后大于:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth))
        //   return;
        // }

        //判断单元格移动方向；
       

        if((g_selectedCellWidth_L-tempWidth)>0)//左单元格变宽了，向右移动了
        {
          moveToLeft=1;
        }
        else
        {
          moveToLeft=0;
        }

        var currentBeforCellOffset=totalOffsetX;//右则单元格X坐标
		    for(var i=0;i<tableLines;i++) //当一列宽变化时，所有行的列该列宽都要变化
		    {   
          
		      console.log('调整单元格大小，当前更新列:'+g_selectedColumn+" 上单元格宽度："+String(tempWidth));   
          
            if(currentSelectedCellIndex-1>=0&currentSelectedCellIndex<tableColumns) //有效列下标限定
            {
          
              //当前更左边单元格调整后，后边的单元格的宽度发生变化，而后边单元格的x坐标等于左边单元格宽+左边所有单元格偏移之和
              if(tempWidth>=15)
              {
               // if(g_selectedColumn==j)
                {

                  // jsonData[i].cells[j-1].width=tempWidth; //左单元格宽设定
                  // currentBeforCellOffset+=tempWidth;
                 

                  var tempWidthAfter=0;
                  
                      if((jsonData[i].cells[currentSelectedCellIndex-1].selected==1||jsonData[i].cells[currentSelectedCellIndex].selected==1)||hadShereLine==1) //当有交集，，要求选择内为有
                      {

                      
                      if(moveToLeft==1)
                      {
                        //左移之后，右单元格宽度变小，计算出变化量 
                        //g_selectedColumn=cellIndex;  //全选中的列
                        //g_selectedRow=rowIndex;     //全选中的行
                        var W_L=g_selectedCellWidth_L;
                        var W_R=g_selectedCellWidth_R;
                        
                        var W_L_1=tempWidth;
                        var W_sub=W_L-W_L_1;

                        var W_R_1_x=W_L-W_sub+totalOffsetX;
                        var W_R_1_W=W_R+W_sub;
                        

                        tempWidthAfter=W_R_1_W;
                        //右单元格 X坐标与W宽变动

                        if(hasAnySelectCellWith==0) //所在列没有选中项
                        {
                          jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                          jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                          jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                        }
                        else
                        {
                          //只对选择的单元格进行更新宽度与起始坐标。
                          if(jsonData[i].cells[g_selectedColumn].selected==true||jsonData[i].cells[g_selectedColumn-1].selected==true)
                          {
                            jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                            jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                            jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                          }
                          
                        }


                        console.log('首列 左移-----【小】【大】 左格宽变化量：'+String(W_sub)+' L_旧宽 ：'+W_L+' 变小 L_现宽：'+W_L_1+ ' R_旧格宽：'+W_R+' 变大 现右格宽：'+String(W_R_1_W));
                        console.log('首列 两单元格移动前宽和：'+String(g_selectedCellWidth_L+g_selectedCellWidth_R)+' 移动后之和'+String(tempWidth+tempWidthAfter));           
                        console.log('首列 左移 g_selectedColumn：'+String(g_selectedColumn)+ ' g_selectedRow:'+String(g_selectedRow)+' Wl:'+String(g_selectedCellWidth_L)+' Wr:' +String(g_selectedCellWidth_R));



                        // if(afterCellWidth>=15)
                        // {
                        //   console.log('最后一个单元格列宽大于15：'+String(afterCellWidth));
                        //       jsonData[i].cells[j].width=afterCellWidth;
                        // }        
                        // else
                        // {  //小于或等于15
                        //   console.log('最后一个单元格列宽 小于15：'+String(afterCellWidth));
                        //   var myWidth=lastTableTotalWidth-totalOffsetX-currentLeftCellWidth-restOffsetX;
                        //   jsonData[i].cells[j].width=myWidth;
                        // }
                      }
                    
                      else  //光标右移：单元格右移，左单元格宽度变大，右单元格宽度后小
                      {
                     
                        var W_L=g_selectedCellWidth_L;
                        var W_R=g_selectedCellWidth_R;
                        
                        var W_L_1=tempWidth;
                        var W_sub=W_L_1-W_L;

                        var W_R_1_x=W_L+W_sub+totalOffsetX;
                        var W_R_1_W=W_R-W_sub;
                        

                        tempWidthAfter=W_R_1_W;
                        //右单元格 X坐标与W宽变动
                        jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                        jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                        jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                        console.log('首列 左移-----【小】【大】 左格宽变化量：'+String(W_sub)+' L_旧宽 ：'+W_L+' 变小 L_现宽：'+W_L_1+ ' R_旧格宽：'+W_R+' 变大 现右格宽：'+String(W_R_1_W));
                        console.log('首列 两单元格移动前宽和：'+String(g_selectedCellWidth_L+g_selectedCellWidth_R)+' 移动后之和'+String(tempWidth+tempWidthAfter));           
                        console.log('首列 左移 g_selectedColumn：'+String(g_selectedColumn)+ ' g_selectedRow:'+String(g_selectedRow)+' Wl:'+String(g_selectedCellWidth_L)+' Wr:' +String(g_selectedCellWidth_R));

                        
                      }
                      
                     }
                 // jsonData[i].cells[j].width=tempWidthAfter;//右边单元格的宽度变化
                 
                }
                // else
                // {

                //   // //其它列，只要移动X坐标

                //   // var tempWidthAfter=0;
                //   // if(moveToLeft==1)
                //   // {
                //   //   //左移之后，右单元格宽度变小，计算出变化量
                //   //   tempWidthAfter=currentRightCellWidth+(Math.abs(currentLeftCellWidth-tempWidth));//前单元格向左移动多出的给右边的单元格
                //   //   console.log('左移-----【小】【大】 左格宽变化量：'+String(Math.abs(tempWidth-currentLeftCellWidth))+' 旧宽 ：'+g_selectedCellWidth_L+' 现宽：'+tempWidth+ ' 右格宽：'+g_selectedCellWidth_R+' 现右格宽：'+tempWidthAfter);
                //   // }
                    
                //   // else 
                //   // {
                  
                //   //   tempWidthAfter=currentRightCellWidth-(Math.abs(tempWidth-currentLeftCellWidth));//前单元格向右，移动的增量部分就是右单元格要减的部分
                //   //   console.log('右移-----【大】【小】 左格宽变化量：'+String(Math.abs(tempWidth-currentLeftCellWidth))+' 旧宽 ：'+currentLeftCellWidth+' 现宽：'+tempWidth+ ' 右格宽：'+currentRightCellWidth+' 现右格宽：'+tempWidthAfter);
                //   // }
                   

                //   // //jsonData[i].cells[j].width=tempWidthAfter;//右边单元格的宽度变化
                //   // afterCellWidth=tempWidthAfter;

                //   // currentBeforCellOffset+=jsonData[i].cells[j-1].width;
                //   // jsonData[i].cells[j].x=currentBeforCellOffset-tableOffsetX;//tableOffsetX+tempWidth-tableOffsetX;//右单元格x设定，为左单元格所有单元格的宽度和
                // }
                
              

               

                //console.log('调整单元格大小，后表格=》马上赋值：'+String(subWidth));

              }

            }
     
		      
			 
		    }
      	//调整后列新父亲单元格
        updateForSellMerging();
		}
		var floatOnBoard=0;
		//isSelecting = false;
		    currentSelection = [];
        updateTotalHeight();// 重新计算表格总高度
        redraw();
        renderPosition(cursorX,cursorY,showText);
        return;
      }
      
      
      $('#cursorCoordinates').text('光标坐标监控全局：(' + cursorX + ', ' + cursorY +')');

 

      //表格选中监测=========================================================================================================
      //遍历行
      var cellStartX = canvasOffset.left+tableOffsetX;
      var cellStartY = canvasOffset.top+tableOffsetY;
      for (var rowIndex = 0; rowIndex < tableLines; rowIndex++) {
      
        var row = jsonData[rowIndex].cells; //表格行单元格数组
         //遍历行中的每个单元格       
         //遍历列 
         if(row.length>0)
         tableColumns=row.length;
         //console.log('=====当前 遍历列:(' + rowIndex +')'+'光标坐标：(' + cursorX + ', ' + cursorY +') 表格共有列数:'+String(tableRows) );
        
				//遍历每一列，是不是在选中范围内
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) { 
          // 获取单元格的位置信息
          console.log();
          var cell = row[cellIndex];//当前行第N个的单元格
          //startX表格起始点x坐标
          //startY表格起始点y坐标
         
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + String(cellStartX) +' cell.y:'+String(cellStartY)+')'+' 光标坐标：(' + cursorX + ','+ cursorY + ')');
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + startX +' cell.y:'+startY+')'+' 光标坐标：(' + cursorX + ', ' + cursorY + ')');
          if (cursorX >= cellStartX && cursorX <= cellStartX + cell.width &&
              cursorY >= cellStartY && cursorY <= cellStartY + cell.height) {
                
         
           // console.log('=====光标在所在 行:(' + rowIndex +' 列:'+cellIndex+')');

       			if(isSelecting==true)
            {
              cursorIsInSideOfCell=1;
            }
            else
            {
              if((cellStartX+offset)<cursorX&& //光标X在左则偏移右边
              cursorX<(cellStartX+cell.width-offset)&&//光标X在右则偏移左边
              (cellStartY+offset)<cursorY&&//光标Y在上则偏移下边
              cursorY<(cellStartY+cell.height-offset))//光标Y在下则偏移上边
              {
                cursorIsInSideOfCell=1;
                //console.log('光标在单元格内心==============');
              }
              else
							{
                cursorIsInSideOfCell=0;
               // console.log('光标不在单元格内心==============');

               if(whereCurIs!=1)
               {
                  g_selectedColumn=cellIndex;  //全选中的列
                  g_selectedRow=rowIndex;     //全选中的行

                  if(g_selectedColumn>0)
                  {
                    g_selectedCellWidth_L=jsonData[g_selectedRow].cells[g_selectedColumn-1].width;
                    g_selectedCellWidth_R=jsonData[g_selectedRow].cells[g_selectedColumn].width;

                  }
                 
               }
              
              }



         	
            }
           

            selectCellLeft=cellStartX;
            selectCellTop=cellStartY;
            selectCellRight=cellStartX+cell.width;
            selectCellBottom=cellStartY+cell.height;
            document.body.style.cursor = 'default';
            currentCell = cell;
            found=1;
            
            if(cellIndex==tableLines)//光标在最后一行
            {
              //console.log('光标在最后一列 =rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')');
            }
            if(curOnBorderAndButtonDown==0) //只有在结构上没有按下按钮时，才进行选中
            {
              currentSelectedCellRowIndex=rowIndex;
              currentSelectedCellIndex=cellIndex;
            }
           
            break;
          }
          cellStartX += cell.width;
        }
        if(found==1 )
        break;
        cellStartX = startX;
        cellStartY += row[0].height;
      }
     
      if(found==1) //当光标在表格上时，显示左上角的移动表格提示图标
      {
        //if (iconVisible) {
         // Draw the icon
         ctx.drawImage(icon, tableOffsetX - icon.width, tableOffsetY - icon.height);
        // console.log('开始画图标===============)');
        //}
      }
      else
      {
        console.log('清除开始画图标===============)');
        isSelecting = false;
        currentSelection = [];
        selectedCells = selectedCells.concat(currentSelection);
        
     
        cursorIsInSideOfCell=0;
       
    
       // redraw();
      }

         //表格选中功能
         if (isSelectingForCell) {
         var canvas = $('#myCanvas');
         var rect = canvas.get(0).getBoundingClientRect();
       
         var x = e.clientX - rect.left;
         var y = e.clientY - rect.top;
   
        x=cursorX-canvasOffset.left-tableOffsetX;
        y=cursorY-canvasOffset.top-tableOffsetY;
     
        //console.log('==========表格选中设置x ：'+String(x)+" y: "+String(y)+' whereCurIs:'+String(whereCurIs));
		

     
        selectionEndX =x;
        selectionEndY =y;
        // Select cells within the dragging area 表单元格的选中操作
        jsonData.forEach(function(rowData, rowIndex) {
          rowData.cells.forEach(function(cell, cellIndex) {
            cell.selected = (
              cell.x < Math.max(selectionStartX, selectionEndX) &&
              cell.x + cell.width > Math.min(selectionStartX, selectionEndX) &&
              cell.y < Math.max(selectionStartY, selectionEndY) &&
              cell.y + cell.height > Math.min(selectionStartY, selectionEndY)
            );
          });
        });
        

        drawTable();
        return;
      }

        //光标表格在最右边。OK 
        if((tableTotalWidth-offset+startX)<cursorX&&cursorX<(tableTotalWidth+offset+startX)&&cursorY>startY&&cursorY<(tableTotalHeight+startY)&&cursorY>startY)
         {
          //光标在表格的最右边上
           curOnTheRightBoarder=1;
           whereCurIs=2;
           var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
           document.body.style.cursor = myCursor;
           //console.log('监测到 光标在表格最右边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
        
         }
         else
         {
           curOnTheRightBoarder=0;

         }


         //curOnTheBottomBoarder
         if((tableTotalHeight-curOffsetY+startY)<cursorY&&cursorY<(tableTotalHeight+curOffsetY+startY))
         {
          //光标在表格的最下边上
           curOnTheBottomBoarder=1;
           whereCurIs=4;
           var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
            document.body.style.cursor = myCursor;
            //console.log('监测到 光标在表格最下边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
         }else
         {
           curOnTheBottomBoarder=0;
         }

        //光标在单元格上方，立即更新光标为上下双箭头,调整高度的情形
       if(cursorX>startX&&cursorX<(tableTotalWidth+startX)&&cursorY>(selectCellTop-offset)&&cursorY<(selectCellTop+offset))
       {
           
            if(currentSelectedCellRowIndex==0)
            {
              //光标在第一行的上边，变光标为单向下箭头
              var myCursor = "url('imgs/down_cursor.png') 8 8,auto";
              document.body.style.cursor = myCursor;
              inRightPosition=1;
              whereCurIs=3;
              //console.log('监测到 光标在单元格首行顶线上-------------------');

            }
            else
            {
              //console.log('监测到  光标在单元格的上边线上 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex);
              var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
              document.body.style.cursor = myCursor;//上下双箭头
              //document.body.style.cursor = 'ns-resize';//上下双箭头
              inRightPosition=1;
              whereCurIs=1;

            }

            floatOnBoard=1;
           
       }
 
   

     
        //光标在左侧边，立即更新光标为左右双箭,调节宽度的情形
       if(cursorX>(selectCellLeft-offset)&&cursorX<(selectCellLeft+offset)&&cursorY>startY&&cursorY<(tableTotalHeight+startY))      
       {

       // console.log('监测到 光标在单元格首行最左边线上：-------------------：：：'+currentSelectedCellIndex);
            if(currentSelectedCellIndex==0)//光标在第一列的左边
            {
               //光标在第一行的上边，变光标为单向下箭头
               var myCursor = "url('imgs/right_cursor.png')8 8, auto";
              document.body.style.cursor = myCursor;
             // console.log('光标在单元格首行最左边线上-------------------');
           
            }
            else
            {
              //document.body.style.cursor = 'ew-resize';//左右双箭头
             // console.log('光标在单元格左边线上-------------------');
             var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
              document.body.style.cursor = myCursor;//左右双箭头
            }
           
           
            floatOnBoard=1;
            inRightPosition=1;//在正确的位置上
            whereCurIs=2;
       }
       

       if(inRightPosition==0)
        {
          document.body.style.cursor = 'default';
        }
       else
        {  
          if(cursorIsInSideOfCell==1)//光标在单元格内心
          {
            floatOnBoard=0;//光标不在边线上
            whereCurIs=5;//光标在单元格内心
          }
          else
          {
          
          }
          

          if(floatOnBoard==1)
          {
            console.log('在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部 ：'+ String(whereCurIs));
            curOnBorder=1;
          }
          else
          {
            curOnBorder=0;
            console.log('不在表格边上悬浮  1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格； 5光标在单元格内部  ：'+ String(whereCurIs));
          }
         
        }

      if(curOnBorderAndButtonDown==1)
      {
       
        if(whereCurIs==1)//光标在单元格上方，调节高度
        { 
          console.log('调整单元格大小，当前所在行:'+currentSelectedCellRowIndex+" 表格列数： "+tableRows);
          if(currentSelectedCellRowIndex!=0)//第一行不处理
          {

            //更新当前行单元格的高度
            for(var i=0;i<tableRows;i++)
            {
              //console.log('调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格高度："+cursorY-canvasOffset);
              //jsonData[currentSelectedCellRowIndex].cells[i].height=cursorY-selectCellTop-canvasOffset;
            }
            
          }

        }



      }
      
   


      
    });
  /*===================================================================
  OnMouseUp 处理鼠标释放事件
  =====================================================================*/

    canvas.addEventListener('mouseup', function(e) {

      if (e.which === 1) 
      {
          e.preventDefault();
      }

      
    if (isSelectingForCell) {
       
      isSelectingForCell=false;
     

              //查询是否有需要合并的单元格,如果有就弹出菜单
        var hasMoreThanOneCellSelected = 0;
        var canSplitCells = 0;
        var canMergeCells = 0;
        var havOneParent=1;
        var parentX=0;
        var parentY=0;
        //如果在选择的单元格中，只有一个格
         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {   
           
             if( cell.selected ==true)
             {
               console.log("Selected==="  );
              hasMoreThanOneCellSelected++;
             
              canMergeCells++;

              if(cell.rowspan>0||cell.colspan>0)
              canSplitCells++;
                 
             }
             
        });
      });

      if(canSplitCells>0)
      {
        highlightButton('splitCells', 1);
      }
      else
      {
        highlightButton('splitCells', 0);
      }

      if(canMergeCells>1)
      {
        highlightButton('MergeCells', 1);
      }
      else
      {
        highlightButton('MergeCells', 0);
      }
     
    
      
      console.log('表格选择鼠标左键被释放。splitCells:'+canSplitCells+' MergeCells:'+canMergeCells);
      
     return;
     ///////////////////////合并完成
  
      }

    if(curOnTheRightBoarder==1)//当调节单元格右边框时，释放。
    {
      
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
	 
      console.log('表格最右侧单元格鼠标左键被释放。');
      return;
    }
    if(isMoveTable==1)
    {
      isMoveTable=false;
      isOnMoveTable=false
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
	  saveState();
      console.log('表格移动状态鼠标左键被释放。');
    }

    if(curOnTheBottomBoarder==1)
    {
      curOnTheBottomBoarder=0;
      curOnTheRightBoarder=0;  
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
      console.log('表格最下行鼠标左键被释放。');
	  saveState();
      return;  
    }

	 if( curOnBorder==1&&curOnBorderAndButtonDown==1)
	 { curOnBorderAndButtonDown=0;//释放单元格调整按钮
     curOnBorder=0;//释放单元格边线
     document.body.style.cursor ='default';//恢复默认光标
     console.log('表格调整键被释放。');
	 saveState();
	   return;//在调整时，不做选择操作。
		 
	 }
   isSelectRegionDrawing = false;    //是否开始选择操作
  
      
    });


  /*===================================================================
      OnMouseDown 处理鼠标左键按下事件
  =====================================================================*/
    canvas.addEventListener('mousedown', function(e) {
		

      // if (event.which === 3) {

      //   curOnTheRightBoarder=0;//释放单元格边线
      //   curOnBorder=0;//释放单元格边线
      //   curOnBorderAndButtonDown=0;//释放单元格调整按钮
      // // 处理鼠标右键事件
      // console.log('鼠标右键被按下。');

      
      // // 阻止默认的右键菜单
      // event.preventDefault();

      //     selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
      //     currentSelection = [selectionStart];
      //     redraw();
      //     return;

      // }

      //leftButtonDown=1;
     		var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		var canvasOffset = canvas.offset();
	
         var cursorX = event.pageX;
         var cursorY = event.pageY;

      	var x = e.clientX - rect.left;
      	var y = e.clientY - rect.top;
          x=cursorX-canvasOffset.left-tableOffsetX;
          y=cursorY-canvasOffset.top-tableOffsetY;
        //selectionStart = getCellFromCoords(x, y);//获取开始单元格
        
      if (cursorIsInSideOfCell==1) {
        isIntoMenuSelection=0;//进入菜单选择状态
        //hideMenu();
        console.log('鼠标左键被按下 获取开始单元格 进入选择状态:-----------------:'+selectionStart+' x="'+String(x)+'" y="'+String(y)+'"');  
        
        isSelectingForCell = true;  
        selectionStartX = x;
        selectionStartY = y;

        jsonData.forEach(function(rowData, rowIndex) {
        rowData.cells.forEach(function(cell, cellIndex) {           
              cell.selected = false;
        });
       
        redraw();
      });



        const cell = getCellByCoords(selectionStartX, selectionStartY);

        if (cell) {
          cell.selected = !cell.selected;
          redraw();
        }
       
        return;
      }


 

      if(isOnMoveTable==1)//光标在表格左上，，置可移动表格
      {
          curOnBorder=1;
          var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
          document.body.style.cursor = myCursor;
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          isMoveTable=1;  //置表格可移动
          console.log('表格左上角 鼠标左键被按下。');
          return;
      }

     //光标在表格的最右边上
     if(curOnTheRightBoarder==1)
     {
          var myCursor = "url('imgs/l_r_cursor.png') 16 16,auto";
          document.body.style.cursor = myCursor;
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          curOnBorder=1;
          console.log('表格最右边上鼠标左键被按下。');
          return;
     }

         //光标在表格的最下边上
    if(curOnTheBottomBoarder==1)
     {
          var myCursor = "url('imgs/u_d_cursor.png') 16 16,auto";
          document.body.style.cursor = myCursor;
          curOnTheBottomBoarder=1; 
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下
          curOnBorder=1; 
          console.log('表格最下边上鼠标左键被按下。');
          return;
     }
          
            
  
    if( curOnBorder==1)         //光标在边框上
    {
          console.log('光标在边框上-鼠标左键被按下。');
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          return;
    }
    
     isSelectRegionDrawing = true;    //是否开始选择操作
  
     var canvas = $('#myCanvas');
     var context = canvas.get(0).getContext('2d');
     var rect = canvas.get(0).getBoundingClientRect();
    
       
        var x = e.clientX - rect.left;
        var y = e.clientY - rect.top;
        x=x-canvasOffset.left-tableOffsetX;
        y=y-canvasOffset.top-tableOffsetY;

        selectionStart = getCellFromCoords(x, y);
        if (selectionStart) {
          isSelecting = true;
          selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
          currentSelection = [selectionStart];
          
        }
  
       
  
      });

      redraw();
   
  });

  
</script>

</body>
</html>
